J. Turolla J. Turolla - 6 months ago 12
Ajax Question

Replacing HTML with content from AJAX return data

I have a script being called in the end of the body of an HTML file. This script sends data collected from multiple input sources in the HTML file to a PHP file that checks if everything is allright and if so, calculates some numbers and output the same HTML file, updating the old numbers with these new calculated numbers.

My question is, can I get this HTML output and replace my old page with the new one, without the need to refresh the page and keeping the script still working?

Part of the Script:



var datas = {action: 'update', subject: sendSub, criteria: changed[5], creditos: changed[4], g1: changed[0], g2: changed[1], g3: changed[2], g4: changed[3]};
$.post('/edit.php', datas).done(function (data) {
//What to do here?
console.log(data);
});




Answer
$.post('/edit.php', datas).done(function (data) {
    $('#idOfSomeDiv').html(data);
});

Whatever the PHP file echos will overwrite the contents of the div with id idOfSomeDiv.

So, if the first element in your body is <div id="wrap">, then do:

$.post('/edit.php', datas).done(function (data) {
    $('#wrap').html(data);
});

and whatever HTML code you echo out from the PHP side will appear on the page. Note that injected elements will no longer work with this type of jQuery:

$('#myAnchortag').click(function(){
    //code in here
});

But it will always work if you use

$(document).on('click', '#myAnchortag', function(){
    //code in here
});

The examples linked in this question may be helpful to review.