PHP return value for jQuery AJAX

I'm new to AJAX and a little confused about what PHP passes back to jQuery. So you have an AJAX function:

$.ajax({ url: '/my/site', data: {action: 'test'}, type: 'post', success: function(output) { alert(output); } }); 

(I took this from ajax to another StackOverflow page.)

But on other resources, they will have a success section that looks like this:

  success: function(data) {functionfoocommandshere} 

Am I just embarrassed by what dictates the purpose of this variable? If PHP eventually resonates with an array:

  echo $myVar; 

How can I get this from AJAX?

+6
source share
4 answers

Ajax-Requests retrieves the entire site. Thus, you will not get any data in the variables, but the whole site in the data parameter. All echoes that you put together will be in this parameter. If you want to get an array, you must convert it to json before.

 echo json_encode($myArray); 

Then you can get it through Ajax this way

 $.ajax({ url: '/my/site', data: {action: 'test'}, dataType: 'json', type: 'post', success: function(output) { alert(output); } }); 
+13
source

In your PHP file, use json_encode to turn the array into a more convenient format for use in Javascript. This way you will have something like:

 echo json_encode($myArray); 

Then, in your JavaScript, the data variable of the success method will contain JSON. Use jQuery parseJSON to convert this to a JavaScript object, which will then be very easy to manipulate. I do not know that you have an array, but you can do something like this:

 $.ajax({ url: '/my/site', data: {action: 'test'}, type: 'post', success: function(data) { var obj = jQuery.parseJSON(data); alert(obj.name[0] === "John"); } }); 

Again, the data variable here will contain all your PHP outputs, but JSON is the usual and convenient way to pass data back to your JavaScript.

+6
source
 <script type="text/javascript"> $.ajax({ url: '/my/site', data: {action: 'test'}, type: 'post', success: function(output) { alert(output); } }); </script> <?php $action = $_POST['action']; echo $action;?> 

Any output that is printed / echo will be returned to the success function. This is convenient if you want to fill the html container with what you need to run in real time.

Once you get this, another option is to use JSON to return variables with values.

+3
source

The data returned by the PHP AJAX function can be extracted from the success block. Here is the manual

  $.ajax({ url: '/my/site', data: {action: 'test'}, type: 'post', dataType: 'json', success: function(output) { //output is the data returned from PHP AJAX function in JSON format alert(output); } }); 
-1
source

All Articles