Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 447
goodbytes Avatar asked Jan 12 '23 18:01

goodbytes


2 Answers

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
});
like image 59
deadlock Avatar answered Jan 16 '23 22:01

deadlock


Add everything you want to an array, then call json_encode on it.

$data = array();

$data[] = $person1;

$data[] = $person2;

echo json_encode($data);
like image 29
maček Avatar answered Jan 16 '23 22:01

maček