Php json to javascript 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.

Читайте также:  Clean html templates free

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:

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!

Источник

Convert and Loop through JSON with PHP and JavaScript Arrays/Objects

If you’re working with JSON (JavaScript Object Notation) and either need to convert a JSON string to array or object and loop through it or vice-versa, take an array or object and convert it to a JSON string to return, both can be done in PHP or JavaScript.

I broke up this post into three sections:

Convert JSON String to PHP Array or Object

PHP >= 5.2.0 features a function, json_decode , that decodes a JSON string into a PHP variable. By default it returns an object. The second parameter accepts a boolean that when set as true , tells it to return the objects as associative arrays. You can learn more about the json_decode function from PHP’s documentation.

 // JSON string $someJSON = '[,,]'; // Convert JSON string to Array $someArray = json_decode($someJSON, true); print_r($someArray); // Dump all data of the Array echo $someArray[0]["name"]; // Access Array data // Convert JSON string to Object $someObject = json_decode($someJSON); print_r($someObject); // Dump all data of the Object echo $someObject[0]->name; // Access Object data ?> 

Loop through PHP Array or Object

Loop through a PHP array or object with a foreach loop.

 // Loop through Array $someArray = . ; // Replace . with your PHP Array foreach ($someArray as $key => $value)  echo $value["name"] . ", " . $value["gender"] . "
"
; > // Loop through Object $someObject = . ; // Replace . with your PHP Object foreach($someObject as $key => $value) echo $value->name . ", " . $value->gender . "
"
; > ?>

Note the differences in accessing the values of an array vs an object.

Convert PHP Array or Object to JSON String

PHP also features a json_encode function to convert an array or object into a string. Read more about the json_encode function from PHP’s documentation.

 // Array $someArray = [ [ "name" => "Jonathan Suh", "gender" => "male" ], [ "name" => "William Philbin", "gender" => "male" ], [ "name" => "Allison McKinnery", "gender" => "female" ] ]; // Convert Array to JSON String $someJSON = json_encode($someArray); echo $someJSON; ?> 

Note that I’m using the short array syntax that’s featured in PHP 5.4+.

 $array = array( "foo" => "bar", "bar" => "foo" ); // as of PHP 5.4 $array = [ "foo" => "bar", "bar" => "foo" ]; ?> 

Convert JSON String to JavaScript Object

JavaScript has a built-in JSON.parse() method that parses a JSON string and returns an object.

script> // Convert JSON String to JavaScript Object var JSONString = '[,,]'; var JSONObject = JSON.parse(JSONString); console.log(JSONObject); // Dump all data of the Object in the console alert(JSONObject[0]["name"]); // Access Object data /script> 

JSON.parse() is very well-supported, but there are browsers that do not support it (i.e.

jQuery 1.x has a $.parseJSON() method that should fill in the gaps for those browsers if you’re needing to support them. You can also use the JSON-js library as a polyfill.

script> // Convert JSON String to JavaScript Object with jQuery var JSONString = ". "; // Replace . with your JSON String var JSONObject = $.parseJSON(JSONString); console.log(JSONObject); // Dump all data of the Object in the console alert(JSONObject[0]["name"]); // Access Object data /script> 

Loop through JavaScript Object

You can then loop through a JavaScript object using a for in loop.

script> // Loop through Object var JSONObject = . ; // Replace . with your JavaScript Object for (var key in JSONObject)  if (JSONObject.hasOwnProperty(key))  console.log(JSONObject[key]["name"] + ", " + JSONObject[key]["gender"]); > > /script> 

Convert JavaScript Object to JSON String

JavaScript has a JSON.stringify method to convert a value into a JSON string.

script> var JSONObject = [  "name": "Jonathan Suh", "gender": "male" >,  "name": "William Philbin", "gender": "male" >,  "name": "Allison McKinnery", "gender": "female" > ]; var JSONString = JSON.stringify(JSONObject); alert(JSONString); /script> 

Like JSON.parse , JSON.stringify is not supported in dinosaur browsers like

You can combine the methods above to create powerful, dynamic implementations on your website or application.

Let’s say you want to get information from a database, safely return the data as JSON, and loop through it dynamically, you can do so with a bit of PHP and JavaScript with Ajax.

Dynamically Get JSON via Ajax and Loop Through JSON

Let’s assume your database structure looks like the following:

Table: people ┌────┬────────────────────┬─────────┐ | id | name | gender | ├────┼────────────────────┼─────────┤ | 0 | Jonathan Suh | male | | 1 | William Philbin | male | | 2 | Allison McKinnery | female | | 3 | Becky Borgster | female | | 4 | Victoria Einsteen | female | └────┴────────────────────┴─────────┘ 

And you want to dynamically get a list of people from the database based on gender, like this:

Let’s start with the front-end file index.html that’ll have a select dropdown with genders to select from, a table to display the results, and the script to handle the Ajax. The JavaScript is written in jQuery.

 id="gender" name="gender">  value="male">Male  value="female">Female   id="people" border="1">  Name Gender    src="http://code.jquery.com/jquery-1.11.1.min.js"> $("#gender").on("change", function()  $.ajax( type: "POST", data:  "gender": $("#gender").val() >, url: "response.php", dataType: "json", success: function(JSONObject)  var peopleHTML = ""; // Loop through Object and create peopleHTML for (var key in JSONObject)  if (JSONObject.hasOwnProperty(key))  peopleHTML += ""; peopleHTML += "" + JSONObject[key]["name"] + ""; peopleHTML += "" + JSONObject[key]["gender"] + ""; peopleHTML += ""; > > // Replace table’s tbody html with peopleHTML $("#people tbody").html(peopleHTML); > >); >);  

Now let’s create a response.php file to handle the back-end logic of getting the information from the database and returning the results as a JSON string.

 // File: response.php // Get POST gender value $gender = $_POST["gender"]; // Connect to the database // replace the parameters with your proper credentials $connection = mysqli_connect("localhost", "username", "password", "database_name"); // Query to run $query = mysqli_query($connection, "SELECT * FROM people WHERE gender = '" . $gender . "'"); // Create empty array to hold query results $someArray = []; // Loop through query and push results into $someArray; while ($row = mysqli_fetch_assoc($query))  array_push($someArray, [ 'name' => $row['name'], 'gender' => $row['gender'] ]); > // Convert the Array to a JSON String and echo it $someJSON = json_encode($someArray); echo $someJSON; ?> 

To get a more in-depth and better example of PHP-JSON-JavaScript/jQuery-Ajax interaction, read my jQuery Ajax Call to PHP Script with JSON Return post.

Jonathan Suh

I’m a multidisciplinary developer & designer. I’m currently with the folks at Planning Center, and I’ve worked with well-known brands and agencies, which include Allstate, Brian Hoff Design, Leo Burnett, and OLSON. More about me. Follow @jonsuh

Selected posts

Источник

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