0

I am working with jQuery AJAX. Using an AJAX call I invoke a PHP page. By default it returns a single value to the success function of AJAX. However I want to retrieve multiple data individually. What can I do?

Here's the jQuery code with AJAX , which returns a single value:

function getTime(){
  $.ajax({
    type: "POST",
    url: "test.php",
    data: {
      fd: sdate,
      sd: edate
    },
    dataType: "text",
    success: function(msg) {
      $("#results").text(msg);
    }
  });
};

Test.php:

echo $days;
echo $hours;
echo $minutes;
echo $seconds;
0

3 Answers 3

3

Typically to return multiple responses, the easiest way to do this is to return a json encoded array. Something like the following should work.

echo json_encode( array(
    "days" => $days,
    "hours" => $hours,
    "minutes" => $minutes,
    "seconds" => $seconds
) );

Since your ajax request has dataType: "text" you will need to parse the response to use it with JSON.parse(msg), however if you changed it to dataType: "json" you would not have to do this step as jQuery will try to auto parse it for you.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey OP, please accept Taplar's spot on answer if it worked and let us know :)
0

your test.php would be like this

echo json_encode( array(
    "days" => $days,
    "hours" => $hours,
    "minutes" => $minutes,
    "seconds" => $seconds
));

and on ajax success

success: function(msg) {
    var result = $.parseJSON(msg);
    console.log(result.days)
}

Comments

0

The proper way is to use array and encode it in JSON.

 echo json_encode( array(
  "days" => $days;
  "hours" => $hours;
  "minutes" => $minutes;
  "seconds" $seconds;
 )
);

but you should use the datatype JSON otherwise you have to parse the response like

    var result = $.parseJSON(response);
    console.log(result.days)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.