Json with php and ajax

How To Return JSON Response in PHP & MySQL using Ajax and jQuery

In this tutorial, I will share with you how to return JSON response in PHP & MySQL using Ajax & jQuery this is useful to display multiple types of data from server response and process it to our client-side using ajax and jquery. Don’t worry this method is easy we are going to use an array from the server and encode it with JSON format.

Basic Example

Let’s do the basics first we will create a new file called basic.php as you can see below code I created an associative array with first_name & last_name name keys. Then I use json_encode to encode the array into JSON format.

Then this is the result when executing it in the browser.

How To Response JSON in PHP & MySQL using jQuery & Ajax

AJAX Integration

For ajax integration we need to create a simple button in our index.html then a simple ajax function to communicate the above code basic.php.

Let’s code our button with HTML.

Then next is our javascript ajax code. We will create our function named basic() inside scripts.js. Here is the code below:

Читайте также:  Html логотип в header

Then if we will click the button «Basic JSON Response» the result will be like this on the console.

How To Response JSON in PHP & MySQL using jQuery & Ajax

Next, we will parse the response JSON so that we can easily call it as JSON. See the code below.

As you can see we add a new line of code «response = JSON.parse(response);». Kindly see the console result after this code.

How To Response JSON in PHP

As you can see from the result above it is clickable now because we already parse it as JSON from a string.

Display by JSON Property

Now we will display the JSON by property like if you want to display the first_name value only. Here is the code update below:

As you can see below we add a new line of code «console.log(«First Name:» + response.first_name);» now in this code, we only access the first_name value.

Display JSON Property in HTML

Now we will display the specific property on your web page. We will update our HTML code below.

Then also our javascript code inside scripts.js. See below code updates.

As you can see above I add new line of code «$(«#json_first_name»).html(«First Name: » + response.first_name);». I call the ID selector «#json_first_name» and use html() function to display the first_name value from your server.

How To Response JSON in PHP

Now since you have the basic knowledge already of how to Response the JSON we will implement the dynamic data using PHP & MySQL with Ajax.

Display Dynamic Data Using Response JSON with PHP & MySQL

I will share with you the easy method to display the dynamic data from your server-side. In this example, we will display the employee in Edit Employee Modal using ajax and jquery.

Display Dynamic Data Using Response JSON with PHP & MySQL

Here is the HTML code inside index.html

Our HTML code for modal inside index.html

  

Edit Employee

Then our PHP code inside get.php as you can see below that I encode the $row variable array from the result query.

query($sql); // Fetch Associative array $row = $results->fetch_assoc(); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>

Then now we will add our javascript code get() function inside scripts.js.

function get() < $(document).delegate("[data-target='#edit-employee-modal']", "click", function() < var employeeId = $(this).attr('data-id'); // Ajax config $.ajax(< type: "GET", //we are using GET method to get data from server side url: 'get.php', // get the route value data: , //set data beforeSend: function () , success: function (response) >); >); >

Loop the JSON Response

Since you already know how to display your JSON response to your web page. Now I will give you an example of how to loop the JSON. Below are the screenshot example on listing the employees via ajax with JSON response.

Before we dive in I will show you first a basic code on how to do it. As you can see in the code below I use «$.each(response, function(key,value)

Kindly check the console result below of the above code.

Loop the JSON Response

So that’s the basic way on how to loop the JSON. So we will apply it in the advance by displaying the list of employees using the bootstrap list group as you can see the result below:

Lop the JSON Response

Now let do the code. First set up our HTML code inside index.html.

Then next our PHP Code inside all.php.

query($sql); // Fetch Associative array $row = $results->fetch_all(MYSQLI_ASSOC); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>

Then now let’s code the javascript for looping the employee’s result via ajax. You will find this code inside scripts.js with all() functions.

function all() < // Ajax config $.ajax(< type: "GET", //we are using GET method to get all record from the server url: 'all.php', // get the route value success: function (response) '; // Loop the parsed JSON $.each(response, function(key,value) < // Our employee list template html += ''; html += "

" + value.first_name +' '+ value.last_name + " (" + value.email + ")" + "

"; html += "

" + value.address + "

"; html += ""; html += ""; html += ''; >); html += '
'; > else < html += '
'; html += 'No records found!'; html += '
'; > // Insert the HTML Template and display all employee records $("#employees-list").html(html); > >); >

Now you have the foundation already about JSON Response from your server-side. I hope this article may help you. To see the action capability of this code just click the «Download» button below.

Thank you for reading. Happy Coding!

Источник

Return JSON response from AJAX using jQuery and PHP

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.

Return JSON response from AJAX using jQuery and PHP

Table of Content

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.

3. Create HTML Layout

Create an HTML table element with an id of “userTable” to display the user list using the AJAX response.

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.

 $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" + "" + (i+1) + "" + "" + username + "" + "" + name + "" + "" + email + "" + ""; $("#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.

Источник

Оцените статью