jon220 jon220 - 6 months ago 9
Ajax Question

PHP Insert content into HTML VIA AJAX

I am using AJAX to run my page dynamically, and I am trying to replace certain content in my html page with certain information that is retrieved from my mysql database. The issue is that I can't just echo it out, because that would echo it out to the url since the php code is being run via ajax and hence an error would throw.

Below is the code for a bit to make things a bit more clear.
AJAX portion

// Display content
$.ajax({
type: "POST",
data: {run: true, providerName: $('#providerName').val(), categoryName: $('#categoryName').val(),titleName: $('#titleName').val() },
url: '/client/lunchnlearn/app/functions/sessionCourseContent.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
$('#payment-form').prop('disabled', true); // TODO: give your html-submit-input-tag an "id" attribute
window.location = response;
}
});


PHP Portion

<?php
$_POST['providerName'];
$_POST['categoryName'];
$_POST['titleName'];




?>


I essentially want to replace the
<div id="content">
with a new content
$content = "......";


I can't just use

preg_replace


because I am not important the html portion from a file, rather the html page is live with the php code running in the background through AJAX.

Any help would be appreciated.

Answer

All you have to do is, set the html of the content div when the data is received by the AJAX.

In the AJAX call change the success callback to update the #content

success: function (response) {//response is value returned from php (for    your example it's "bye bye"
            $('#payment-form').prop('disabled', true); // TODO: give your html-submit-input-tag an "id" attribute
            $('#content').html(response);
    }

Then in the php file you are calling through AJAX, put the content you want to get returned.

<?php
$_POST['providerName'];
$_POST['categoryName'];
$_POST['titleName'];
//do whatever you want here

//return the content you want to show.
return $content;
?>

That's all you have to do.