Calling jquery ajax function to update a row in a table is not taking place until a refresh is made. calling the php script in server from javascript is done perfectly but changes are not reflected on page intended . . . How can that be solved?
3 Answers
You can achieve this in a few simple steps:
- Once updated, invoke the function to get data for that edited row OR recall the function to get all data.
- Once you fetched the data, you can use jQuery to edit your table html.
The easiest way is to get all data. So you can use jQuery.empty() and then reinitialize your table.
One of two things:
- Re-run the function that initially gets the data for your table once the edit AJAX function completes.
- Return the newly-updated MySQL table within the GET response object.
I'd recommend the latter, to keep things concise.
EDIT
Apologies for inconsistencies, I'm out of practice with jQuery, however, the gist is the same
var populateTable = function(tableData){
//whatever you do to populate your table
}
$(document).ready(function(){
$.get("www.your.site.com/getData", function(data){
populateTable(data);
})
})
const submitEdits = function(){
$.ajax({
method: "POST", //Or whichever method you use
url: "www.your.site.com/sendData",
data: <your data here>
})
.done(function( response ) {
populateTable(response.data);
});
}
-
-
-
That answer costs a lot regarding of performance especially when database grows– OsahadyCommented Oct 30, 2018 at 7:24
After inserting data using ajax, suppose your data is successfully saved.
Fetch all the row from table in the same ajax call and make an html of it in the same ajax call
$html = '';
foreach($data as $key=>$val){
$html.='<tr>';
$html .= '<td>'.$val['name'].'</td>';
$html .= '<td>'.$val['email'].'</td>';
$html .='</tr>';
}//as per your response come.
and then in successful ajax response whatever html you made return in response such as
return json_encode(array('message'=>'success','table_html'=>$html));
and in ajax success replace html of table with the new html. such as
$('#table').html(response.table_html);
if you have a body head foot in table you made then replace only the body of table by giving id to it.
-
The message undefined is returned when trying to reach response.table_html– OsahadyCommented Oct 27, 2018 at 21:23
-
first of all you need to console first your ajax reponse first test that your ajax reponse contain table_html or not after having it you can go further. Commented Oct 28, 2018 at 4:56
-
Might want to give a read to stackoverflow.com/help/formatting :) Commented Nov 7, 2018 at 14:24