Jhanvi thanki
Jhanvi thanki

Reputation: 3

php + jquery + ajax fetch multiple value

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;

Upvotes: 0

Views: 632

Answers (3)

Umer Hayat
Umer Hayat

Reputation: 35

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)

Upvotes: 0

anulal sreeranjanan
anulal sreeranjanan

Reputation: 352

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

Upvotes: 0

Taplar
Taplar

Reputation: 24965

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.

Upvotes: 3

Related Questions