tags:

views:

75

answers:

3

Hi,

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?

+1  A: 

It's an argument passed to your success funtion:

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

Nick Craver
Exactly! I see that you've beat me to it...
Aaron
A: 

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);
    }
});
Aaron
I thought so, but alert(data) is popping up null. And I know $output in the PHP is not null. I'll try textStatus.
A: 

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