jQuery Ajax returns the whole page
I've just been making the move from pure JavaScript to jQuery because of, well, peer pressure, and finding it frustrating. In particular, getting whole pages of PHP back from an Ajax POST request. I have read and re-read this page several times in the past two days when this kept happening. In the end, the problem in both cases that I'd either spelled the php url wrong in the Ajax setup or put the wrong path to the file.
Sometimes it's the easiest little things that trip you up!
I hope that this will save somebody out there some time...
Sophia, In your case, you should not send your data to a php file that, if viewed by a web browser, displays a website page. You should send your information to a php file that only returns the data that you would like to see returned.
So instead of "index.php", create a file called something like "my-ajax-script.php". That file should include any necessary "include()" files to connect to the database and your php function files (ie: for sanitizing the POST data). Then the file should have the code that processes the POST data, and echo's out the data complete with some html tags. This data will be inserted into your existing DOM (html markup).
So when you have this on your index.php
at the beginning?:
<?php
if (isset($_POST["testAjax"])) {
echo $_POST["testAjax"];
}
?>
If this script is outputting further text then of course this will also be recieved by the Ajax call. You can put exit()
after the echo to prevent the script from being processed further:
if (isset($_POST["testAjax"])) {
echo $_POST["testAjax"];
exit();
}
Also use dataType: 'text'
as the value you return is obviously not HTML.
Or as others suggest, create a new page that is responsible for dealing with the Ajax request. If you are doing more than just outputting the received value (i.e. more complex operations) you should do this anyway.
That's how it works. You're requesting index.php
via AJAX, so you'll get whatever the contents of index.php
are.
If you want a particular value, make a new PHP page that outputs just that value, and request that URL's contents instead.