goodbytes goodbytes - 6 months ago 148
Ajax Question

How to get multiple responses to a single ajax request in php

I am making a web app, where I want to provide a search function. I am sending the searched name with an ajax request, and i want to pull the records of that particular person. But since there are many details that are to be displayed, I am finding it difficult to get the response. (I am not able to get more than one response at a time)

I want to know, if there is a way to get multiple responses for a single request, or a way to send all my variables in the target PHP file to the requesting javascript file as an array or something.

Thank you. If this question is asked before, please provide the link.

Answer

Use JSON as the datatype to communicate between PHP(Backend) and Javascript(Frontend). Example:

PHP

<? 
$person = array("name"=>"Jon Skeet","Reputation"=>"Infinitely Increasing");
header("Content-Type: application/json");
echo json_encode($person);
?>

Javascript/jQuery

$.ajax({
  url: "your_script.php",
  dataType: "JSON"

}).success(function(person) {
  alert(person.name) //alerts Jon Skeet
});
Comments