Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return data from PHP to a jQuery ajax call

Tags:

jquery

ajax

I am posting some data using ajax. I want to manipulate that data and return to to the calling jQuery script.

Here is my jQuery:

$.ajax({   type: "POST",   url: "somescript.php",   datatype: "html",   data: dataString,   success: function() {     //do something;     } }); 

Here is my somescript.php on the server:

  <?php     //manipulate data     $output = some_function(); //function outputs a comma-separated string     return $output;   ?> 

Am I doing this correctly on the server side, and how do I access the return string when the ajax call completes?

like image 959
user191688 Avatar asked Mar 09 '10 16:03

user191688


People also ask

Can we return a value from AJAX call?

You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.

How PHP can be used in an AJAX application?

Create an XMLHttpRequest object. Create the function to be executed when the server response is ready. Send the request off to a PHP file (gethint. php) on the server.


2 Answers

I figured it out. Need to use echo in PHP instead of return.

<?php    $output = some_function();   echo $output; ?>  

And the jQ:

success: function(data) {   doSomething(data); } 
like image 200
user191688 Avatar answered Sep 20 '22 10:09

user191688


It's an argument passed to your success function:

$.ajax({   type: "POST",   url: "somescript.php",   datatype: "html",   data: dataString,   success: function(data) {     alert(data);     } }); 

The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)

like image 40
Nick Craver Avatar answered Sep 20 '22 10:09

Nick Craver