Return json data with php

JSON stands for JavaScript Object Notation, it is a data-interchange format which is also been used lớn passing data from the server.

Bạn đang xem: Return json data with php

It is the best and effective way when need to return multiple values as a response from the PHP. script to the jQuery.

You couldn’t directly return an array from AJAX, it must have sầu converted in the valid format.

In this case, you can either use XML or JSON format.

In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array inkhổng lồ JSON format using the json_encode() function in the PHPhường.

On the basis of response show data in tabular format.



1. Table structure

I am using users table in the tutorial 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_TIMESTAMPhường ON UPDATE CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create config.php for database configuration.

Completed Code


Create a for displaying user danh mục using AJAX response.

Xem thêm: Azonal Là Gì - Regions And Zones

Completed Code Username Name E-Mail

4. PHP

Create ajaxfile.php tệp tin for handling AJAX request.

Initialize the array with the user details (id, username, name, & email) and before return converting it to JSON format using the json_encode() function.

Completed Code

$id, "username" => $username, "name" => $name, "email" => $email);}// Encoding array in JSON formatemang lại json_encode($return_arr);

5. jQuery

On document ready state send an AJAX GET request.

Loop through all response values và append a new row to on AJAX successfully callbachồng.

Note – For handling JSON response you have lớn phối dataType: "JSON" while sending AJAX request.

Completed Code

$(document).ready(function(){ $.ajax({ url: "ajaxtệp tin.php", type: "get", dataType: "JSON", success: function(response){ var len = response.length; for(var i=0; i

6. Demo

View Demo

7. Conclusion

In this tutorial, I showed how you can return the JSON response và handle it in jQuery AJAX.

You can convert the PHP. array in JSON format with json_encode() function & return as a response. Set dataType: "JSON" when skết thúc AJAX request.

If you found this tutorial helpful then don"t forget khổng lồ mô tả.
Are you want khổng lồ get implementation help, or modify or extend the functionality of this script? Submit paid service request.