I'm completely new to ajax and trying to find a workaround how to complete these scenario since I can't find any that works for me.
I'm finding a way to populate the dropdown selection using foreach using AJAX. How I'm able to achieve it? I'm completely stuck here. Here's the AJAX script.
$('#kelompokumur_id').change(function() {
var id = $(this).val();
$.ajax({
url: "{{url('fetch-anak')}}/"+id,
type: 'get',
dataType: 'json',
success: function(response) {
if(response.success){
let dataArray = response.data
$('#data_anak').empty()
let res = dataArray.map((person, index) => {
let list = `
<tr class="btn-reveal-trigger">
<td>${person.user.name}</td>
<td></td>
<td class="text-end">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" name="absensi[${person.id}]">
<option value="">Pilih Absensi</option>
<option value="1">PRESENT</option>
<option value="2">PERMIT</option>
<option value="3">SICK</option>
<option value="4">ALPHA</option>
</select>
</td>
</tr>
`;
$('#data_anak').append(list);
});
}
}
});
});
And here's the script that I tried to get the collection,
return view('anak.absensi._inputabsen', compact('data_ku'));```
I tried this method, but it returns null since it's the closest I can get. Others show errors.
let list = `
<tr class="btn-reveal-trigger">
<td>${person.user.name}</td>
<td></td>
<td class="text-end">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" name="absensi[${person.id}]">`
#foreach($data_ku -> item)
<option value="{{$item -> id}}">{{$item -> attendance -> status}</option>
#endforeach
`</select>
</td>
</tr>
`;
On controller:
public function create()
{
$data_ku = KelompokUmur::all();
$kabsen = kodeabsensi::all();
// dd($kabsen->toArray());
return view('anak.absensi._inputabsen', compact('data_ku', 'kabsen'));
}
when I dd($data_ku), this returns:
0 => array:6 [▼
"id" => 1
"kode_absen" => "AM"
"nama_absen" => "Anak Malas"
"keterangan" => "Anak Malas"
"created_at" => "2023-01-13T17:27:49.000000Z"
"updated_at" => "2023-01-13T17:27:49.000000Z"
]
Any help would be appreciated, thanks!
While in the *.blade.php file you can do something like this. I did it outside of the script tags but you can also perform it inside:
#php
$data_ku_item_options = '';
foreach ($data_ku as $item) {
$data_ku_item_options .= "<option value=\"" . $item->id . "\">" . $item->attendance->status . "</option>";
}
#endphp
<script>
$('#kelompokumur_id').change(function () {
var id = $(this).val();
$.ajax({
url: "{{url('fetch-anak')}}/" + id,
type: 'get',
dataType: 'json',
success: function (response) {
if (response.success) {
let dataArray = response.data
$('#data_anak').empty()
let res = dataArray.map((person, index) => {
var options = "{{ $data_ku_item_options }}";
let list = `
<tr class="btn-reveal-trigger">
<td>${person.user.name}</td>
<td></td>
<td class="text-end">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" name="absensi[${person.id}]">
${options}
</select>
</td>
</tr>
`;
$('#data_anak').append(list);
});
}
}
});
});
</script>
And $data_ku = KelompokUmur::all(); change this line to:
$data_ku = KelompokUmur::with('attendance')->get();
Use this to get the collection of array in the JS
var absen = {!! json_encode($kabsen->toArray()) !!}
Then iterate it using $.each method in jQuery
$.each(absen, function(index, value) {
list += `<option value="${value.id}">${value.kode_absen}</option>`;
});
list +=
Related
I tried to create plugin that to customize woocommerce payments setting page , I create it with ajax code but i cant complete the plugin and make it work.
My js code
(function ($) {
$(document).on('change', '.wsd-plugin-controller-toggle', function () { //checkbox
let initiator = $(this),
data = {
'action_type': initiator.data('state'),
'plugin_slug': initiator.data('plugin-slug')
};
$.ajax({
url: plugins_controller.rest.endpoints.update_state,
type: "POST",
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', plugins_controller.rest.nonce);
initiator.closest('.wsd-toggler').find('.wsd-loading').toggleClass('visible');
},
success: function (response) {
console.log(response);
initiator.data('state', response.state);
if (initiator.data('reload')) {
location.reload();
}
$(document).trigger('wsd-plugin-state-updated', [initiator, response]);
initiator.closest('.wsd-toggler').find('.wsd-loading').toggleClass('visible');
},
error: function (response) {
console.log('error ', response);
initiator.prop('checked', false);
$(document).trigger('wsd-plugin-state-update-failed', [initiator, response]);
initiator.closest('.wsd-toggler').find('.wsd-loading').toggleClass('visible');
}
});
});
})(jQuery);
and my html code
<td class="title">
My Fatoorah
</td>
<td class="status">
<div class="wsd-toggler">
<input id="toggler-csCeE5" type="checkbox" class="wsd-toggler-input wsd-plugin-controller-toggle" data-plugin-slug="myfatoorah-woocommerce/myfatoorah-woocommerce.php" data-state="activate">
<label for="toggler-csCeE5" class="check-trail wsd-toggler-shape">
<span class="check-handler wsd-toggler-handler"></span>
</label>
<img src="\wordpress\wp-content\plugins\store_settings\assets\images\spinner.svg" class="wsd-loading" alt="loading">
</div>
</td>
<td class="moderate">
<select class="wsd-payment-popup-select wsd-hidden" onchange="location = this.value;">
<option selected="" disabled="" hidden="">إدارة</option>
<option value="/wordpress/wp-admin/admin.php?page=wc-settings&tab=checkout§ion=myfatoorah_direct">
الدفع المباشر
</option>
<option value="/wordpress/wp-admin/admin.php?page=wc-settings&tab=checkout§ion=myfatoorah_v2">
كارت
</option>
</select>
</td>
</tr>
And my main page php i add
add_action('admin_enqueue_scripts', 'load_payment_style');
function load_payment_style()
{
wp_enqueue_style('plugins_controller_style', plugins_url('style.css', __FILE__));
wp_enqueue_script('plugins_controller', plugins_url('plugins_controller.js', __FILE__));
wp_localize_script( 'plugins_controller', 'plugins_controller',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ,
'ajax_nonce' => wp_create_nonce( 'plugins_controller' ) ) );
}
I need to chang payment state (active / deactive) by toggler like this
payment setting page
thank you
I am certain this question has been asked before, I don't think there is anything unique about my situation but let me explain. I have my Index View (Parent), on that Index View there is a partial View Dataset Contacts "links" (child), I have an Add Contact button, which pops a Modal and allows me to submit the form data to add to the database, when I return I want to only refresh the partial view of links. Note: the Controller Action Dataset_Contacts below needs to fire in order to refresh the partial view (child). It might go without saying, but I don't see this happening with my current code. Any assistance will be appreciated.
on my Index View index.cshtml I have the following code to render my partial View
<div class="section_container2">
#{ Html.RenderAction("Dataset_Contacts", "Home"); }
</div>
Here is the controller:
[ChildActionOnly]
public ActionResult Dataset_Contacts()
{
// Retrieve contacts in the Dataset (Contact)
//Hosted web API REST Service base url
string Baseurl = "http://localhost:4251/";
var returned = new Dataset_Contact_View();
var dataset = new Dataset();
var contacts = new List<Contact>();
var contact_types = new List<Contact_Type>();
using (var client = new HttpClient())
{
dataset = JsonConvert.DeserializeObject<Dataset>(datasetResponse);
contact_types = JsonConvert.DeserializeObject<List<Contact_Type>>(ContactTypeResponse);
// Set up the UI
var ds_contact = new List<ContactView>();
foreach (Contact c in dataset.Contact)
{
foreach (Contact_Type t in contact_types)
{
if (c.Contact_Type_ID == t.Contact_Type_ID)
{
var cv = new ContactView();
cv.contact_id = c.Contact_ID;
cv.contact_type = t.Description;
returned.Dataset_Contacts.Add(cv);
}
}
}
}
return PartialView(returned);
}
Here is my Partial View Dataset_Contacts.cshtml
#model ResearchDataInventoryWeb.Models.Dataset_Contact_View
<table>
#{
var count = 1;
foreach (var ct in Model.Dataset_Contacts)
{
if (count == 1)
{
#Html.Raw("<tr>")
#Html.Raw("<td>")
<span class="link" style="margin-left:10px;">#ct.contact_type</span>
#Html.Raw("</td>")
count++;
}
else if (count == 2)
{
#Html.Raw("<td>")
<span class="link" style="margin-left:300px;">#ct.contact_type</span>
#Html.Raw("</td>")
#Html.Raw("</tr>")
count = 1;
}
}
}
</table>
Also on my Index.cshtml is my Add Contact button, which pops a modal
<div style="float:right;">
<span class="link" style="padding-right:5px;">Add</span>
</div>
jquery for the Modal:
var AddContact = function () {
var url = "../Home/AddContact"
$("#myModalBody").load(url, function () {
$("#myModal").modal("show");
})
};
Controller action for AddContact
public ActionResult AddContact()
{
return PartialView();
}
Modal for AddContact.cshtml
#model ResearchDataInventoryWeb.Models.Contact
<form id="contactForm1">
<div class="section_header2">Contact</div>
<div style="padding-top:5px;">
<table>
<tr>
<td>
<span class="display-label">UCID/Booth ID</span>
</td>
<td>
#Html.TextBoxFor(model => model.Booth_UCID, new { placeholder = "<Booth/UCID>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Type</span>
</td>
<td>
<select class="input-box" id="contact_type">
<option value="contact_type">Contact Type*</option>
<option value="dataset_admin">Dataset Admin</option>
<option value="dataset_Provider">Dataset Provider</option>
<option value="department">Department</option>
<option value="external_collaborator">External Collaborator</option>
<option value="principal_investigator">Principal Investigator</option>
<option value="research_center">Research Center</option>
<option value="vendor">Vendor</option>
</select>
</td>
</tr>
<tr>
<td>
<span class="display-label">Name</span>
</td>
<td>
#Html.TextBoxFor(model => model.First_Name, new { placeholder = "<First Name>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Last_Name, new { placeholder = "<Last Name>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Email</span>
</td>
<td>
#Html.TextBoxFor(model => model.Email, new { placeholder = "<Email 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Email_2, new { placeholder = "<Email 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Phone</span>
</td>
<td>
#Html.TextBoxFor(model => model.Phone_Number, new { placeholder = "<Phone 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Phone_Number_2, new { placeholder = "<Phone 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Job Title</span>
</td>
<td>
#Html.TextBoxFor(model => model.Title_Role, new { placeholder = "<Job Title>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Organization</span>
</td>
<td>
<input class="input-box" type="text" placeholder="<Organization>" />
</td>
</tr>
</table>
<div style="padding-left:10px; margin-top:10px;">
<textarea rows="3" placeholder="Notes"></textarea>
</div>
</div>
<div class="centerButton" style="margin-top: 30px;">
<div style="margin-left:30px">
<submit id="btnSubmit" class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">SAVE</span></submit>
</div>
<div style="margin-left:30px">
<submit class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">REMOVE</span></submit>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var frm = $('#contactForm1').serialize()
$.ajax({
type: "POST",
url: "/Home/AddContact/",
data: frm,
success: function () {
$("#myModal").modal("hide");
}
})
})
})
</script>
and lastly Action for [HttpPost] AddContact(Contact data)
[HttpPost]
public ActionResult AddContact(Contact data)
{
// Update the Database here
return View();
}
My solution:
1. Change ActionResult to JsonResult
{
// Update the Database code
// END
return Json(new
{
dbUpdateResult = "success"
});
}
2. In Ajax:
//Ajax code
...
success: function (ajaxRespond) {
if(ajaxRespond.dbUpdateResult == "success"){
$("#myModal").modal("hide");
reloadTable()
}
}
Then you can use 1:
function reloadTable(){
$('#CONTAINER_ID').load('#Url.Action("Dataset_Contacts", "Home")');
}
Or 2:
function reloadTable(){
let myurl = '#Url.Action("Dataset_Contacts", "Home")';
$.ajax({
type: "GET",
url: myurl,
success: function (data, textStatus, jqXHR) {
$("#CONTAINER_ID").html(data);
},
error: function (requestObject, error, errorThrown) {
console.log(requestObject, error, errorThrown);
alert("Error: can not update table")
}
});
}
So you reload your partial view after successful dbupdate. Please tell me, if I'm wrong...
I want to know something in Laravel. I want a dropdown for classes so when the user selects any class and press the submit button then the users related to that specific class will be displayed below in the table... Is it possible?
Below is the code I did for getting the data but I want this data to refer to my table in the HTML because there is something more I want and I can't add those things to the ajax table
//My ajax
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if(classID) {
$.ajax({
url: '/myform/ajax/'+classID,
type: "GET",
dataType: "json",
success:function(data) {
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td>' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name+ ' ' + value.last_name + '</td> <tr>';
});
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
//Controller
public function index(Request $request){
$classes = StudentsClass::pluck('class_name', 'id')->all();
return view('admin.students.attendance.index', compact( 'classes'));
}
public function mytableAjax($id) {
$students = Student::where('students_class_id', $id)->get();
return json_encode($students);
}
//My view
<select name="students_class_id" class="form-control" style="width:350px">
<option value="">--- Select State ---</option>
#foreach ($classes as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
<table id="studentsData" class="table table-striped table-bordered table-list-search">
<thead>
<tr>
<th>#</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<select class="form-control" id="gender">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>
</td>
</tr>
</tbody>
</table>
<a class="fas fa-folder-open btn btn-success float-right mb-4 mr-2"> Save</a>
</div>
Check the following code that will add the attendance column for every row :
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/myform/ajax/' + classID,
type: "GET",
dataType: "json",
success: function(data) {
var attendance = `<div class="form-group">
<select class="form-control" id="gender" name="attendance[]">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>`;
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td><input type="hidden" value="'+value.id+'" name="id[]">' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name + ' ' + value.last_name + '</td> <td> ' + attendance + '</td> <tr>';
});
$('#studentsData tbody').html(markup);
var thead_markup += '<tr> <th>A</th> <th>B</th> <th>C</th> <td>D</th> <tr>';
$('#studentsData thead').html(thead_markup);
}
});
}
});
});
It depends upon your code, if you are using ajax datatables api then here is a similar example:
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
} );
Reference: datatables.net multi filter select
If you are not using datatables api and do not want ajax then use below code and change according to your need:
$("#selectDropdown").on("change", function () {
var value = $(this).val();
$("table tr").each(function (index) {
if (index != 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) != 0) {
$(this).hide();
}
else {
$(this).show();
}
}
});
});
I have a dropdown with option to select if you want to see domens that are expiring in given date.
But once i pick date i will get pure json code with right result.
This is my form above table
<form method="post" action="{{ action('DomenController#tabela') }}" id="klijent_rok" onchange="document.getElementById('klijent_rok').submit()">
#csrf
<div class="form-group row">
<label for="istice_za" class="ml-md-auto col-form-label text-md-left" style="padding-right: 10px;">Ističu u roku od:</label>
<select name="istice_za" id="istice_za" class="form-control" style="width: 140px" size="1">
<option value="99" #if($istice_za == '99') selected='selected' #endif>-neodređeno-</option>
<option value="7" #if($istice_za == '7') selected='selected' #endif>za 7 dana</option>
<option value="30" #if($istice_za == '30') selected='selected' #endif>za 30 dana</option>
<option value="60" #if($istice_za == '60') selected='selected' #endif>za 60 dana</option>
<option value="istekli" #if($istice_za == 'istekli') selected='selected' #endif>istekli</option>
</select>
Poništite filtere
</div>
</form>
And this is mine controller for server side Datatable
if(!empty($request->istice_za) && $request->istice_za != 99) {
$date = Carbon::now();
$new_date = Carbon::now();
if($request->istice_za != 'istekli') {
if($request->istice_za == 7) {
$istice_za = 7;
$new_date->addDays(7);
}
if($request->istice_za == 30) {
$istice_za = 30;
$new_date->addDays(30);
}
if($request->istice_za == 60) {
$istice_za = 60;
$new_date->addDays(60);
}
$domen = Domen::where('datum_end', '<', $new_date)
->Where('datum_end', '>', $date)
->with('klijent');
}
else {
$domen = Domen::where('datum_end', '<', $date)->with('klijent');
$istice_za = 'istekli';
}
}
else {
$domen = Domen::with('klijent');
$istice_za = 99;
}
return datatables()->of($domen)->make(true);
And these are my routes
Route::get('/lista-domena/tabela', 'DomenController#tabela');
Route::post('/lista-domena/tabela', 'DomenController#tabela');
What am I doing wrong and not getting that data in my table?
For first, your code is not running the query, you need to add ->get() or first() to get the data.
$domen = Domen::where('datum_end', '<', $date)->with('klijent')->get();
Or,
$domen = Domen::with('klijent')->get();
I managed to solve it. The problem was that i didn't send data from select to my controller. I edited my form to be like this:
<form method="post" action="{{ action('DomenController#tabela') }}" id="klijent_rok">
And then added this in script:
$('#klijent_rok').on('change', function(e) {
table.draw();
});
and changed Ajax to this:
ajax: {
url: '/lista-domena/tabela',
data: function ( d ) {
d.istice_za = $('#istice_za').val();
},
}...
Html:
<table id="affected-requirement-table" class="table table-hover table-sm table-bordered">
<!--Table head-->
<thead>
<tr>
<th>Requirements</th>
<th>Effect Type</th>
</tr>
</thead>
<!--Table head-->
<!--Table body-->
<tbody>
<!-- Ajax Load -->
</tbody>
<!--Table body-->
</table>
Jquery
$(document).ready(function () {
var affectedRequirementsTable = $('#affected-requirement-table').DataTable({
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,
processing: true,
serverSide: true,
bFilter: false,
"bInfo": false,
"bPaginate": true,
"ordering": false,
"bLengthChange": false,
ajax: {
url: '{!! \Illuminate\Support\Facades\URL::to("cr/requirements-datatables") !!}'
},
columns: [
{data: 'number'},
{data: 'effect-type'}
],
// "fnCreatedRow" : function (row, data, dataIndex) {
// var div = document.createElement("div");
// $(div).html('<select name= "changeRequest[]" class="form-control effect-type-select" id="mySelect"> <option selected="selected" value="None">None</option> <option value="Addition">Addition</option> <option value="Deletion">Deletion</option> </select>');
// $(row).children("td:last-child").append(div);
// }
});
// draw the table
affectedRequirementsTable.draw();
$("#affected-requirement-table").on('change',".effect-type-select",function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
console.log(valueSelected);
});
})
routes:
Route::get('cr/requirements-datatables', "ChangeRequestController#requirementsAndEffectTypesDatatables");
Controller:
public function requirementsAndEffectTypesDatatables(ChangeRequests $request)
{
$changeRequest = DB::table('requirement')->select(['number','id']);
return DataTables::of($changeRequest)->addColumn('effect-type', function ($changeRequest) {
return '
<select name= "changeRequest[]" class="form-control effect-type-select" id="mySelect">
<option selected="selected" value="None">None</option>
<option value="Addition">Addition</option>
<option value="Deletion">Deletion</option>
</select>';
})->rawColumns(['effect-type'])->make(true);
}
I create a page on which there is a table with a paginator. I post a request to specify the output of rows from the database for insertion into the table. However, the paginator remains old. How should I change it?
Get a request for a new page or insert all the HTML code that comes from the controller is not satisfied.
Code view:
<table class="table table-bordered text-center table-hover" id="table_list">
<thead>
<tr>
<th>id</th>
</tr>
<tr>
<td><input type="text" class="form-control" id="id_card" value=""></td>
</tr>
</thead>
<tbody>
#if($dats)
#foreach($dats as $data)
<tr>
<td><div class="help" data-id="{{ $data['id'] }}"> {{$data['id']}}</div></td>
</tr>
#endforeach
#endif
</tbody>
</table>
{{ $dats->links() }} // After completing the ajax, the link remains old and allows you to navigate through the old table
Js code in view:
$('#id_card').on('keyup', function(){ // search
value = $(this).val();
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}'
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data); // update table
//update paginator links
},
error: function(data){
console.log(data);
}
})
})
Code controller
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
print($str);
return;
}
In Laravel 5, you could do it by changing your controller to something like this.
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
return response()->json([
'rows' => $str,
'links' => $models->render()
], 200);
}
In your ajax response, render the links with $('ul.pagination').replaceWith(data.links);
eg.
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}',
page: page
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data.rows); // update table
$('ul.pagination').replaceWith(data.links); // update links
},
error: function(data){
console.log(data);
}
});