I have a jquery-ajax function that sends data to a php script and the problem is with the return value, it returns the whole page instead of single value.
Thank you
Updated 2020: If you are using MVC framework, then the url SHOULD NOT be 'index.php',instead using full directory:
url: "http://localhost/mvc/controller/function/param1/param2",
Old answer 2019:
In my case, anyone who has the same issue try using
require_once
instead of require
in your bootstrap php file to prevent a whole page re-render a second time through out the system.
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.
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.
Use condition to verify if $_POST empty in you main page or index.php to not send the whole page in response ajax
<?php
if(empty($_POST)){ ?>
//
<html>
the header pages
the body
the include pages
the scripts pages
the footer
<?php } ?>
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).
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...