How to return data from PHP to a jQuery ajax call

JqueryAjax

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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);
}

Solution 2 - Jquery

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

Solution 3 - Jquery

based on accepted answer

$output = some_function();
  echo $output;

if it results array then use json_encode it will result json array which is supportable by javascript

$output = some_function();
  echo json_encode($output);

If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword

$output = some_function();
  echo $output;
exit;

Solution 4 - Jquery

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser191688View Question on Stackoverflow
Solution 1 - Jqueryuser191688View Answer on Stackoverflow
Solution 2 - JqueryNick CraverView Answer on Stackoverflow
Solution 3 - JqueryDEEPAKView Answer on Stackoverflow
Solution 4 - JqueryAaronView Answer on Stackoverflow