views:

174

answers:

3

Dear all, 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 for your time and help.

$("#ajaxBtn").click(function(){
var inputText = $("#testText").val();

$.ajax({ type: "POST",
url: "index.php",
data: "testAjax="+inputText,
dataType: "html",
success: function(html){
alert(html);
}
 });
});         
+3  A: 

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.

ceejayoz
Thanks! I changed the request to "ajax.php" page and it works fine!
Sophia Gavish
+1  A: 

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).

superUntitled
+1  A: 

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.

Felix Kling