JSON or JavaScript Object Notation is a widely used transmitting format for passing data between a server and a web application. It is the most efficient way to return multiple values as a response from the PHP script to jQuery.
It is not possible to return an array directly from AJAX, and it must be converted into a valid format. You can either use the XML or JSON format.
In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.
On the basis of response show data in tabular format.
Table of Content
- Table structure
- Database connection
- Create HTML Layout
- AJAX – Returning JSON Response from PHP
- jQuery – AJAX Request and JSON Response
- Demo
- Conclusion
1. Table structure
I am using users
table in the example.
CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Database connection
Create config.php
for database configuration.
<?php $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
3. Create HTML Layout
Create an HTML table element with an id of “userTable” to display the user list using the AJAX response.
<div class="container"> <table id="userTable" border="1" > <thead> <tr> <th width="5%">S.no</th> <th width="20%">Username</th> <th width="20%">Name</th> <th width="30%">Email</th> </tr> </thead> <tbody></tbody> </table> </div>
4. AJAX – Returning JSON Response from PHP
Create ajaxfile.php
to handle AJAX requests. Inside the file, create an array called $return_arr
to store the response that will be sent back to the client.
Next, fetch all records from the users
table and loop through them. For each user, add their details (id, username, name, and email) to the $return_arr
array.
Finally, using json_encode()
function convert $return_arr
Array to JSON format before returning it to the client side.
<?php include "config.php"; $return_arr = array(); $query = "SELECT * FROM users ORDER BY NAME"; $result = mysqli_query($con,$query); while($row = mysqli_fetch_array($result)){ $id = $row['id']; $username = $row['username']; $name = $row['name']; $email = $row['email']; $return_arr[] = array("id" => $id, "username" => $username, "name" => $name, "email" => $email); } // Encoding array in JSON format echo json_encode($return_arr);
5. jQuery – AJAX Request and JSON Response
An AJAX GET request is sent to ajaxfile.php
once the document has reached the ready state. A new row is added to the table with the ID userTable
after a successful callback, which loops through all response values.
In AJAX request set dataType
to 'json'
to handle the JSON response or you can use JSON.parse()
to convert returned JSON string to an object.
$(document).ready(function(){ $.ajax({ url: 'ajaxfile.php', type: 'get', dataType: 'JSON', success: function(response){ var len = response.length; for(var i=0; i<len; i++){ var id = response[i].id; var username = response[i].username; var name = response[i].name; var email = response[i].email; var tr_str = "<tr>" + "<td align='center'>" + (i+1) + "</td>" + "<td align='center'>" + username + "</td>" + "<td align='center'>" + name + "</td>" + "<td align='center'>" + email + "</td>" + "</tr>"; $("#userTable tbody").append(tr_str); } } }); });
6. Demo
7. Conclusion
The PHP array must be encoded into JSON using the json_encode() function before a response can be returned. To handle returned JSON response you can either set dataType to ‘json’ or use JSON.parse() function.
With practice and further exploration, you can use these concepts to build more advanced and interactive web applications.
Additionally, you may refer to a tutorial to learn how to send a JavaScript array with an AJAX request.
If you found this tutorial helpful then don't forget to share.
Thank you. It’s the most simple explanation of sending multiple objects from php.
Thanks for reading.
HI I WANT CREATE FUNCTION AND CALL THIS FUNCTION UING AJAX
LIKE
FUNCTION SELECT()
{
$return_arr = array();
$query = “SELECT * FROM users ORDER BY NAME”;
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$id = $row[‘id’];
$username = $row[‘username’];
$name = $row[‘name’];
$email = $row[’email’];
$return_arr[] = array(“id” => $id,
“username” => $username,
“name” => $name,
“email” => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
You can do this way –
jQuery –
PHP file (ajaxFile.php) –
Hey, so lets say the users have their profile saved n a database
CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`updatedOn` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
how would I post this when they login fetching their profile using their username(unique) and email(unique) as sessions to display on homepage
Hi Sanni,
You can check the $_SESSION variable on the AJAX file. If the session is set means the user is logged in then fetch its records otherwise return an empty array.
Thank you. this helps a lot.
Thank You. it is very simple and easy to understand ! thank you very much….!
Hope we will have more angular JS demos.
Thank you
otimo artigo! Me ajudou muito. Abraco do Brasil
Thanks Mr Singh
Simple and straightforward explanation 🙂
Thank you very much! I couldn’t find a solution to this from SO and this saved hours of my time! 🙂
Simple! Thank you.
You’re welcome.
Thank you very much this help me a lot
You’re welcome.
Hi nicely explained very easily, but i have a question is once button is clicked its ok.
but if we click again button it show the same data again.
i want to stop that only allowed once can u pls help me out
Hi Savan,
You can do this by creating a Boolean variable to store the status if the button is clicked or not. On button clicked fetch records and assign true to the variable. Only fetch record if a variable has false value.
hy i want to ask about “response”. In my case my .php that work for parsing a array to json format work properly but in my main .php, its just show undefine in every response[i] and length of response become 631. i dont know what is a cause . can you please help me to identified the problem?
Hi Eric,
Can you mail me your code at makitweb@gmail.com so I can check?
Great job
Thanks.
how should i do this in a prepared statement?
Hi Joe,
You can do it like this –
I have the same issue as Eric (November 24, 2019).
what is the answer please?
Hi Colin,
Can you show me your jQuery AJAX code?
Hi Yogesh,
Here it is.
$(document).ready(function(){
/*alert(‘test’);*/
$.ajax({
url: ‘ajaxfile.php’,
type: ‘get’,
dataType: ‘JSON’,
success: function(response){
/*alert(response);*/
var len = response.length;
/*console.log(response);*/
for(var i=0; i<3; i++){
var id = response[i].id;
var username = response[i].username;
var name = response[i].name;
var email = response[i].email;
console.log(response);
console.log(response[i].username);
var tr_str = "” +
“” + (i+1) + “” +
“” + username + “” +
“” + name + “” +
“” + email + “” +
“”;
$(“#userTable tbody”).append(tr_str);
}
}
});
});
Can you share your code at makitweb@gmail.com so I can check it?
Hi Yogesh Singh, thank for this mini tutorial. How to know if the json data is captured by the ajax script? Apply your example to a code I’m working on and it doesn’t give me any results, the php file generated by the json is found in another directory
Hi Valter,
To know what data AJAX script is returning check the browser network tab. Click on the AJAX file name.
Hi Yogesh, thanks for your answer, I look into every detail and nothing, in fact, I used your tutorial on my website and nothing, I got zero results, the only difference is the html code, in my case the html code is inside a php variable echoed in an index file, that’s the only difference. I don’t know what else I can do, I’m stuck in this stage for more than three days and nothing, would you give me a hand in this matter? I would really appreciate it
Can you share your code at makitweb@gmail.com so I can check it?
Hi Yogesh, don’t worry, I was able to solve the problem, anyway thanks
Bundle of than for the best project demo files ..!
it helped me a lot
I’m glad you found it useful.
hey great work!
i am newbie.
i need help!
look i have 2 pages,
1st page is waiting for response of 2nd page. but i need, when i submit form on 2nd page on isset($_POST[‘submit’]){send response to 1st page }. util then 1st page should wait for the response.
give me all possible ways to communicate between two pages
Is there any body i need little help plz. I’m trying to access id from ajax response that is coming from database but when when i alert it or console it i only get single bracket ( { ).
$.ajax({
type : ‘post’,
url : ‘main_controller/verify_email_for_password_reset’,
data : {
verify : verify
},
success : function(data)
{
var html = ‘ Change’;
$(‘#test’).html(html);
}
});
});
$(‘#test’).on(‘click’,’#change_password’,function(){
var id = $(this).data(‘id’);
alert(id);
hi, please help me.
i have try your example but i don’t see the value of response…
html:
ptf
tipologia_ptf
tipo_ptf
venditore
$(document).ready(function(){
$.ajax({
url: ‘trend_contratti_TOT.php’,
type: ‘get’,
dataType: ‘JSON’,
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var ptf = response[i].ptf;
var tipologia_ptf = response[i].tipologia_ptf;
var tipo_ptf = response[i].tipo_ptf;
var venditore = response[i].venditore;
var tr_str = "” +
“” + ptf + “” +
“” + tipologia_ptf + “” +
“” + tipo_ptf + “” +
“” + venditore + “” +
“”;
$(“#userTable tbody”).append(tr_str);
}
}
});
});
PHP:
$ptf,
“tipologia_ptf” => $tipologia_ptf,
“tipo_ptf” => $tipo_ptf,
“venditore” => $venditore);
}
// Encoding array in JSON format
echo json_encode($return_arr);
$conn->close();
?>
Hello Sir,
Sir i have a class and created a function for example:
public static function getdetails(){
//when this function called using ajax we do db query and return result this is working fine.
echo json_encode($results);
}
Now what should i do if i need this function again inside this class for some other function like :
public static function activateuser(){
$result = self::getdetails(); // here this shows NULL as get details function already displayed records or something…
}
So, can you please help me how to do this as i could not want to use same function again and again for same results.
Thanks
Ashish
Thank you for this tutorial! In my case I need to send JSON data to the ajax file, then it uses that JSON for tasks and returns JSON back again to the first file. How would I do that?
Thanks!
Hi Sir, Is it possible to implement your code without looping?
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var username = response[i].username;
var name = response[i].name;
var email = response[i].email;
And make it like this?
success: function(response){
var id = response.id;
var username = response.username;
var name = response.name;
var email = response.email;
Yogesh ,
Can you perhaps show me what I’m doing wrong here. I am very new to this. I am trying to do slide down child row in a datatable. I know I am close.
function format ( object ) {
let data=object;
let x = ”;
let txt=”;
console.log(object);
//data=object;
try {
if (x != undefined) {
// Executes for declared variables that are not undefined nor null
console.log( ‘X is okay ‘ + x)
} // (Nothing happens)
} catch (x) {
console.log(‘Catch ‘ + x) // ReferenceError: x is not defined
}
//Json.parse(data);
for (x in data) {
txt += data[x].Tillid + ‘ Line No:’ + data[x].LineNo + ‘ ‘ +data[x].Productcode + ‘ ‘ + data[x].ProductDescription+’ ‘ + parseFloat(data[x].LineSalePriceIncDisc).toFixed(2) +”\n”;
return ”+
”+
”+
‘Till Name:’+
”+ data[x].Tillid + ”+
‘Product Description:’+
”+”+”+
”+
”+
‘Customer Name:’+
”+ console.log(data[x].ProductDescription) +”+
”+
”+
‘Extra info:’+
‘And any further details here (images etc)…’+
”+
”;
}
}
{Tillid: “MAINTILL”, LineNo: “1”, Productcode: “15479”, ProductDescription: “Cadent 1 Blk Lagre”, SingleSalePrice: “380.0000”, …}
{Tillid: “MAINTILL”, LineNo: “2”, Productcode: “11571”, ProductDescription: “Helm 58-62 Mission EVO Silver”, SingleSalePrice: “19.9900”, …}
Sorry meant to say I am getting undefined in the tillname area of the slider i.e. txt is showing undefined. The slider is working okay it’s just what is being returned. The console log shows the data.
function format ( object ) {
const q=object;
let x = ”;
let txt=”;
console.log(‘In format ‘ +object);
//data=object;
console.log(q[0][“Tillid”]);
try {
if (x != undefined) {
console.log( ‘X is okay ‘ + x)
for (x in data) {
txt+= q[x].Tillid + ‘ ‘ + q[x].ProductDescription +’ ‘ + “\n”;
}
}
} catch (x) {
console.log(‘Catch ‘ + x) // ReferenceError: x is not defined
}
return ”+
”+
”+
‘Till Name:’+
”+ txt +”+
‘Customers Invoices:’+
”+”+”+
”+
”+
‘Customer Name:’+
”+ ‘view‘ +”+
”+
”+
‘Extra info:’+
‘And any further details here (images etc)…’+
”+
”;
}
Hi Sean,
Can you share the code at makitweb@gmail.com so I can check it?
So i completely copied the code to test it, but the Table ist displayed in my case, but if i go to the ajaxfile.php i can see the data but it isnt displayed on the html site… whats the problem for that ?
Im a beginner sorry