I use datatable to show my data. I store data in ajax request & append that after a successful response. Data is appended successfully. But the problem is datatable is not updated when appending an item. If I reload the page then It works. See image red mark. Data is appended but datatable is not updated.
Here is my ajax success response
success: function(response) {
if (response.status == true) {
var href = "{{ route('home') }}/";
$('#dataTable tbody').prepend( "<tr class='data" + response.data.id + "'>" +
"<td><img src='" + href + "storage/sliders/" + response.data.image + "'></td>" +
"<td>" + response.data.name + "</td>" +
"<td>" + response.data.title+ "</td>" +
"</tr>" );
}
}
How to auto-refresh datatable after ajax success?
try like bellow:-
var table = $('#table_id').DataTable({
//ajax method that gets data from databases.
});
use this method to refresh your table:
table.ajax.reload();
if it gives an error like
DataTables warning: table id=table_id- Invalid JSON response
then use the below function before adding data to the table to solve the error:
table.clear()
Related
I am creating table rows with delete button in it, but the problem is I am not able to find that delete button outside Ajax. So I use Ajax inside Ajax logic but I have to do it again and again. I want to use the button created by Ajax to call separate Ajax call.
My script is:
$.ajax({
url : "{{url('addtocart')}}",
type : "POST",
data : {_token: CSRF_TOKEN, username:username, userType:userType,
table_no:table_no, order_no:order_no, cname:cname,
tname:tname, dname:dname, dish_qty:dish_qty,
chefnote:chefnote
},
success : function(data){
//console.log(data);
$('#cartOrder').empty();
for(var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
function drawRow(rowData) {
var row = $("<tr />")
row.empty();
$("#cartOrder").append(row);
row.append($("<td contenteditable='true' onBlur='saveToDb(this, "+rowData.dish+")'>" + rowData.dish + "</td>"));
row.append($("<td contenteditable='true' id='xyz'>" + rowData.dish_qty + "</td>"));
row.append($("<td contenteditable='true'>" + rowData.chefnote + "</td>"));
row.append($("<td>"+"<button class='btn btn-primary' value='"+rowData.ord_id+"'>" +"Edit"+"</button>"+" | " +"<button class='btn btn-primary' id='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>" + "</td>"));
}
//delete cart order
$('tBody #deletecart').click(function(e){
e.preventDefault();
$.get("{{url('deletecart')}}",{id:$(this).val()},function(data){
// console.log(data);
$.ajax({
url : "{{url('getcart')}}",
type : 'GET',
data : {table_no:table_no},
success : function(data){
console.log(data);
$('#cartOrder').empty();
for(var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
function drawRow(rowData) {
var row = $("<tr />")
row.empty();
$("#cartOrder").append(row);
row.append($("<td contenteditable='true'>" + rowData.dish + "</td>"));
row.append($("<td contenteditable='true'>" + rowData.dish_qty + "</td>"));
row.append($("<td contenteditable='true'>" + rowData.chefnote + "</td>"));
row.append($("<td>"+"<button class='btn btn-primary' value='"+rowData.ord_id+"'>" +"Edit"+"</button>"+" | " +"<button class='btn btn-primary' id='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>" + "</td>"));
}
}
});
});
});
}
});
});
As you can see, first time I use Ajax to load data into table. But when I click delete, the row gets deleted from database but not from the view. So I load that table data on delete button in second Ajax. But it is not working the second time I click the delete button. It is may be because I am calling parent delete function. How can I do this?
The problem is with ID. You can not use same id at multiple places in same page. In your case, you need to use class instead of id.
Replace this :
<button class='btn btn-primary' id='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>
with ?
<button class='btn btn-primary' class='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>
As you are creating this html in loop so id is repeating. So use class and override your delete function :
$('tBody .deletecart').click(function(e){
I have a form created from the following action,
USER selects a link
using $('#livesearch').on('click', 'a', function(e){}); accesses and gets some information from MySQL db through .php via AJAX call
based on the response data, it populates the content div in the bootstrap 3 modal window
in the modal window populated via javascript, I have another form field for submission,
in this form field, I'm trying to do a POST/Response through AJAX call and it just takes me to the php page and not doing anything..
suppose is it not possible to AJAX on a form field dynamically generated by another AJAX call?
to explain in more detail, I've included my codes here below,
for point 3 and 4,
// AJAX call from a link selected
$('#livesearch').on('click', 'a', function(e) {
var selectedValue = $(this).attr("value");
$.ajax({
type: 'POST',
async: true,
url: "../../../avocado/private/functions/measures.php",
data: {name:selectedValue},
success: function(data, status){
var selectedData = JSON.parse(data);
console.log(selectedData);
// populates contents for the modal body
$.each( selectedData, function( i, val ) {
document.getElementById("measures").innerHTML+= "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[i][6]+"</td><td rowspan=\"4\">Quantity"
+ "<form role=\"form\" action=\"../../../avocado/private/functions/food_save.php\" id=\"measure_quantity\" method=\"POST\">"
+ "<div class=\"form-group\">"
+ "<label class=\"sr-only\" for=\"quantity\">quantity</label>"
+ "<input type=\"Number\" name=\"quantity\" class=\"form-control\" id=\"quantity\" placeholder=\"desc"+i+"\">"
+ "<input type=\"hidden\" id=\"food_name\" name=\"food_name\" value=\""+selectedValue+"\">"
+ "<input type=\"hidden\" name=\"food_type\" value=\"nutrients\">"
+ "<input type=\"hidden\" name=\"food_id\" value=\""+selectedData[i][0]+"\">"
+ "<input type=\"hidden\" name=\"measures_id\" value=\""+selectedData[i][4]+"\">"
+ "<input type=\"hidden\" name=\"grams\" value=\""+selectedData[i][10]+"\">"
+ "</div>"
+ "<button type=\"submit\" class=\"btn btn-default\">Save</button>"
+ "</form>"
+ "</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[i][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[i][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[i][9]+"</td></tr>"
+ "<tr><th>(g)</th><td>"+selectedData[i][10]+"</td></tr>"
+ "</table>";
});
},
error: function(xhr, status, err) {
alert(status + ": " + err);
}
});
});
for point 5,
$('#measure_quantity').submit(function(){
postData = $(measure_quantity).serialize();
$.post("../../../avocado/private/functions/food_save.php",postData+'&action=submit&ajaxrequest=1',function(data, status){
$("#measure_quantity").before(data);
});
});
Try something like the below:
$( "#measure_quantity" ).on( "submit", function( event ) {
event.preventDefault();
postData = $("#measure_quantity").serialize();
$.post("../../../avocado/private/functions/food_save.php",postData+'&action=submit&ajaxrequest=1',function(data, status){
$("#measure_quantity").before(data);
});
});
This will still work with dom elements that do not exist on the initial page load because of the .on() statement.
Also its not something silly like the typo:
postData = $(measure_quantity).serialize();
Should be...
postData = $("#measure_quantity").serialize();
I have found the problem, for dynamically loaded contents such as this case, I have to add a selector parameter otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content
$(document.body).on('submit', '#measure_quantity' ,function(e){
console.log("heeeellllo");
e.preventDefault();
var postData = $("#measure_quantity").serialize();
$.post("../../../avocado/private/functions/food_save.php",postData+'&action=submit&ajaxrequest=1',function(data, status){
$("#measure_quantity").before(data);
});
});
But then again, I have another question... if the modal window has already been populated with the form, direct bound method should work fine right? still kind of cloudy on what direct and delegated bound means.. and what the difference between the two is,
I have a JSON file that is being used to autopopulate some select boxes. Every now and then (I can't recreate the fault, it appears to be random) the items in the drop down do not display until I refresh the page.
I've checked the console and log etc, the file is loading fine, no errors are appearing and I'm a little at a loss.
Any ideas?
Example of JSON and the script that reads it below.
Thanks.
"radAbsorbed" : [
{
"value" : "rad",
"name" : "Rad(rd)"
},
{
"value" : "millirad",
"name" : "Millirad(mrd)"
}]
and the script:
<script>
// JSON:
// The key is the class identifier, temp, area etc etc
// Value is being used for both ID and Value when the list is being populated
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
</script>
EDIT:
Updated script.
$(document).ready(function(){
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
});
EDIT: Thanks everyone for their help, it seems to be working fine and looked like an amateur mistake on my part.
I think the problem is that your script is sometimes running before the document is ready.
Try wrapping your code in a document ready function:
$(function() {
$.getJSON(...)
// ...
});
This will make it so that the code doesn't execute before the elements it's affecting are created. For instance, if your code executes before the element with the ID from gets created, then $('#from') will not match any elements, and it won't work.
Wrapping it in a document ready function will make sure that your code waits until the elements have been created before executing.
Alternatively, you could move your <script> tag out of the head and place it right after the #from element in your HTML. This might help it load slightly faster.
So I got a select menu and when an user select an option, it calls a post function via ajax that generates some table rows via PHP and then it returns the html coding for it. In it, there is an Add button.
What I am trying to do is that when the user clicks the add button, a form shows up.
But for some reason, it is not working...
Here is the code:
$(document).ready(function () {
$(".add_form").hide();
$("#console").change(function () {
var id = $(this).val();
var dataString = 'console_id=' + id;
$.ajax({
type: "POST",
url: "generate-games-list",
data: dataString,
cache: false,
success: function (html) {
$("#games_table_body").html(html);
}
});
});
$(".add_button").click(function () {
alert("HELLO");
var id = this.id;
$.post('manage_games', 'game_id=' + id, function (response) {
alert(response);
});
$("#game_id").val(id);
$(".add_form").show();
});
});
Here is the PHP code that returns the table rows:
$console = Console::find(Input::get('console_id'));
$type = GameType::find(Input::get('type_id'));
if(!Input::has('console_id'))
return "Error";
else{
foreach($console->games()->get() as $console_game){
$available_consoles_string = "";
$game_types_string = "";
//Get all the consoles the game can be played on
foreach($console_game->consoles()->orderBy('name', 'asc')->get() as $available_consoles){
$available_consoles_string = $available_consoles_string . " " .$available_consoles->name .", ";
}
//Get all the types that the game falls in
foreach($console_game->types()->orderBy('type', 'asc')->get() as $game_types){
$game_types_string = $game_types_string . " " .$game_types->type .", ";
}
return "<tr><td>" .$console_game->name. "</td><td>". $available_consoles_string. "</td><td>" .$game_types_string. "</td><td><input type='button' id='" .$console_game->id. "' class='add_button' value='Add'/> / View</td></tr>";
}
}
Any idea why it is not working? When I mean not working, I mean the alert is not showing up but I am not getting any error on the Chrome Console...
Thanks,
Ara
Simply use .on():
$(document).on("click", ".add_button", function(){
// your event code
});
When your js runs a click event is attached to all current elements with the .add_button class. However, you're adding extra buttons via ajax and these won't have trigger the same click event.
To fix this use the code above. It attaches the event to the document so even if you add buttons once the page has loaded the click event will be triggered by them.
Here is my funciton:
function getEmployeeList() {
alert("hello world3!");
$.getJSON(serviceURL + 'getemployees.php', function(data) {
alert("hello world4!");
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '"/>' +
'<h4>' + employee.firstName + ' ' + employee.lastName + '</h4>' +
'<p>' + employee.title + '</p>' +
'<span class="ui-li-count">' + employee.reportCount + '</span></a></li>');
});
$('#employeeList').listview('refresh');
});
}
When the page is ready, it will run this function, however, nothing is appended.
I have tested, all php can return correct format. What wrongs?? Please please help me...
You need to add the external host (in my case was mysite.localhost) in PhoneGap.plist under the "ExternalHosts" key.
I presume serviceURL is not on the same domain.
In that case you add callback=? in the end, and jQuery does some magic:
$.getJSON(serviceURL + 'getemployees.php?callback=?', function(data) {
...
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
jQuery API