How to refresh datatables on ajax success? - javascript

I have seen many stackoverflow questions on this and none of the answers have worked for me.
I have a DataTable that is initialized on the template inside <script> </script> tags, but the JS function that is handling the ajax call is in a different file and is loaded on page load.
I have data coming into the ajax function as a JSON object, I am also replacing the rows of the table with the data I get from the JSON object, but the datatables part of it is not refreshed (For ex: If row is deleted and table is empty, empty message is not shown).
How do I do refresh/re-initialization of the datatables inside of the ajax success? I was pointed here, but the documentation is really vague there and was not much help.
Here's my code:
leads.html
$(document).ready(function()
{
$('#leads_table').DataTable( {
"bInfo": false,
"language": {
"emptyTable": "There are no leads yet"
}
});
})
JS Function for Ajax:
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data)
{
$('#leads_table').DataTable({...}) // Tried this, but complains about a duplicate initialization
//How do I refresh here?
$("#leads_table tbody").html(data.html_leads_list);
}
})

Related

AJAX isn't setting a PHP $_POST varibale so it's returning as 'Undefined'

I'm new to AJAX and not so good at PHP. I'm trying to simply send a string saying "Hello" to my PHP page using the JQuery $.AJAX function. So far I have successfully got AJAX to send the information to the page and log it in the console but the data doesn't get stored into the POST variable.
Please keep in mind I'm not being lazy by coming to this forum and asking for help but I have no other choice because I've been searching for about 2 days now on how to fix this problem and haven't found anything that's worked.
Here's my HTML (order.html) - This isn't all my HTML but it's all you will need):
<html>
<body>
<form method="POST">
<button id="order-btn" type="submit" formaction="PHP/sendMail.php">Order</button>
</form>
<!-- JavaScript/JQuery links -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="JS/order.js"></script>
</body>
</html>
Here's my JavaScript (order.js - Once again, I'm only providing necessary code)
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "PHP/sendMail.php",
type: "POST",
data: {data: txt},
dataType: "html",
asyc: true,
success: function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
Here's my PHP(sendMail.PHP - I'm only providing necessary code)
<?php
if(isset($_POST['data'])) {
$data = $_POST['data'];
echo $data;
} else {
echo "Failed to grab data.";
}
Just to clarify, in my actual code the URL is the full URL of my website page.
Let me know in the comments if you would like to see the site to get a better understanding of how and why I need this feature to work.
UPDATE & SOLUTION:
From the help I received I now understand that AJAX will only update information on the current page (So, for example, if you have an AJAX function on index.html then you can only run AJAX on that page and can't transfer information across pages)
To solve my problem I stopped sending users to the sendMail.php page and instead changed the HTML content of the page I was currently on (order.html) in the $.ajax success method.
Here's the updated JavaScript code:
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "order.html",
type: 'POST',
data: {data: txt},
dataType: 'html',
success: function(data){
if(parseInt(data)!=0) {
$("body").html(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
I'd like to thank everyone that helped :)
$.ajax({ //create an ajax request to load_page.php
type: “POST”,
url: “load-page.php”,
data: {page:url}, //with the page number as a parameter
dataType: “html”, //expect html to be returned
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$(‘#pageContent’).html(msg); //load the returned html into
pageContet
$(‘#loading’).css(‘visibility’,’hidden’);//and hide the rotating
gif
}
});
Like in above example load-page.php is called so data returned is going to dispaly in pageContent which is the id of some div etc and this div is not on load-page.php this div is on the page from where this ajax request is sent.
may be it will make sence
reference link: Reference Link!
It's not like this way as you have called sendMail.php this file and the data returned will be available in the page from where it was called.
Let suppose with button click on page A you called sendMail.php, so the ajax response returned to page A not to sendmAil.php.
First thing, garantees that your API is working. Using a toolchain for API, like postman or insomnia.
If your api is returning what you want, then you go to your javascript code, because I don't see any problem in your code. I even used your code and worked.
Then use session
session_start(); //at the top
$_SESSION['mydata'] = $data; // something like it
but as far as I know it's necessary to refresh the page for session to work. please try it

Jquery Ajax Datatable reload

I am using jquery datatable to list my database values.
I want create a country and its state in same page while that initially the state datatable is empty.Once I create country the country id is generated and can create state with that country id in same page.It also created fine but the problem is datatable is not reloading it should show the state which was created but its not showing.The problem is country id which is generated is not passing to the ajax parameter in datatable while reloading it.
country_id=$("#country_id").val();
dataTable = $('#example').DataTable( {
"serverSide": true,
// Load data for the table's content from an Ajax source
"ajax": {
"url": datatable_url,
"type": "POST",
data:{country_id: $("#country_id").val()},
error: function () { // error handling
$(".table-grid-error").html("");
$("#table").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#table-grid_processing").css("display", "none");
}
},
],
});
I reloading it by
$.ajax({
url: 'url',
type: "POST",
data: {
//data
},
success: function (data) {
reload_tabless();
},
function reload_tabless() {
dataTable.ajax.reload(null, false); //reload datatable ajax
}
Please help me rectify it.
it looks like you have the url hard coded to the string 'url' in the code that should do the ajax call before calling reload_tabless() which most probably makes the ajax call to fail, thus not executing the success callback.
I don't think you need that extra ajax call. Simply execute reload_tabless instead of that ajax call.
Use "destroy": true inside DataTable section and call DataTable function again.
It will reload DataTable without postback.

How to refresh PHP file with AJAX

Okay, so I searched the web as much as I could and I couldn't find the solution on my problem. I also typed the question and searched for an answer as I saw similar questions to mine. Didn't help. I tried numerous solutions.
Well I have an index page that loads includes/data.php which loads the data from database and echo the .js format that is then loaded by function and display data on the page, so I have at the end of my index.php something like this:
<script type="text/javascript" src="includes/data.php"></script>
On the same index page I have a form that inserts data to database. If you refresh the page I will see refreshed includes/data.php along with new data I just inputted.
I am trying to implement AJAX so that when I click on the button I insert the data to database (already achieved this) and to refresh content of includes/data.php and index.php so it shows data right away without refreshing the index.php. This is my AJAX code:
$('#addtocal').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
// This is the part where I am stuck.
},
error : function(){
$(".error").fadeIn(2000);
$(".error").fadeOut(2000);
}
});
return false;
});
Just to mention that #calendar is where main jquery function is loading the html content based on the info from /includes/data.php. Thank you in advance for any help you can provide and let me know if you need any other information from me in order to better assist me.
P.S. I saw many suggested using .load() to load content from includes/data.php but that is not working in my case as the content from includes/data.php needs to serve other jquery function that creates html on the fly and and place it in #calendar
I got it to work. What I did I inser aditional $.ajax inside the $.ajax and on completion and I called again again the jquery that uses /includes/data.php
so the code would be something like this:
$('#addtocal').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
$.ajax({
url: "../includes/data.php",
dataType: "script",
cache: true
}).done(function() {
// Here I called other jquery function that uses ../includes/data.php
});
},
error : function(){
$(".error").fadeIn(2000);
$(".error").fadeOut(2000);
}
});
return false;
});
Thanks for your help anyway #Half Crazed gave me a clue so I get the $.getScript function and saw the way to call .js again so I tried and it worked.

table positioning with AJAX to PHP post

I have a jQuery script that sends POST data via AJAX to a php file that then creates a table. I have used firebug to check the console and everything gets created properly. On the success: I reload the window and the table isn't displayed.
I know the table html was created properly from the php file because I commented out the reload so I could see exactly what it created) I have lots of things displayed on my page and would like the table in a particular spot. How can I get the table to actually display where I want it to?
<script>
$(document).ready(function () {
$("#stayinfobutton").click(function () {
var id = $('#id').val();
var dataString = {
id: id
};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/table_auto_guests.php",
data: dataString,
cache: false,
/*success: function(html)
{
window.location.reload(true);
}*/
});
});
});
</script>
The window.location call will reload a new page in the browser window, this will loose the data returned to the ajax call by the server.
Usually the response to Ajax calls is loaded directly into your page, something like:
success: function(html)
{
$('#guestsTable').html(html);
$('userForm').hide();
}
I made up the guestsTable div and userForm names, ;).
The return data may need some coercing to make it into html (I'm assuming your using JQuery), hopefully the php script will set it to html/text in the header, also dataType: html can be passed in the $.ajax({...}) call.
Alternatively, if the classes/table_auto_guests.php returns a full page which you want to load in the browser, Ajax may not be what you are looking for. This post contains code on how to submit the data as a form, and load the result as a new page.

Posting JSON string to PHP page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.

Categories