JSON Javascript AJAX jQuery HTML PHP Example MORE

How to Return JSON response from AJAX using jQuery and PHP


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;

config.php

<?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());
}

<table id='userTable'>

<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>

ajaxfile.php

<?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);

$(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);
            }

        }
    });
});