How to Get JSON Data from PHP Script using jQuery Ajax


The jQuery ajax is very useful when you want to post or get data from PHP script without page refresh. Generally, you return the string to Ajax call for updating a part of the web page. But sometimes requires getting the object or array data from PHP file for showing values in the different area. Using $.ajax() method in jQuery you can get JSON data from a file and set in the HTML element.

In this tutorial, we will show you how to process ajax request using jQuery and call a PHP script that returns JSON data. The PHP script will fetch data from the MySQL database and returns JSON data to Ajax. The returned data is parsed using JavaScript and set values to the specific elements.

jQuery AJAX Call to PHP Script with JSON Return

For your better understanding, we will fetch user details from the database based on the user ID via Ajax call using jQuery, PHP, and MySQL.

Database Table Creation

The users table holds the basic information of the users. Our example script will retrieve user details from this demo (users) table.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

HTML Code

Initially, an input box is displayed to provide the user ID whose details you want to retrieve. The “Get Details” button initiates an Ajax request and the respective user details are displayed under the input box.

<input type="text" id="user_id" />
<input type="button" id="getUser" value="Get Details"/>
<div class="user-content" style="display: none;">
    <h4>User Details</h4>
    <p>Name: <span id="userName"></span></p>
    <p>Email: <span id="userEmail"></span></p>
    <p>Phone: <span id="userPhone"></span></p>
    <p>Register Date: <span id="userCreated"></span></p>
</div>

JavaScript Code (jQuery & AJAX)

$.ajax() method perform an Ajax request and post the user ID to a PHP file to get the user details from the database. If the request succeeds the data returned from the server as the specified format in the dataType parameter. In our example script, JSON is specified in dataType, the data will be returned as JSON format. The parsed JSON data sets to the respective element content.

<script>
$(document).ready(function(){
    $('#getUser').on('click',function(){
        var user_id = $('#user_id').val();
        $.ajax({
            type:'POST',
            url:'getData.php',
            dataType: "json",
            data:{user_id:user_id},
            success:function(data){
                if(data.status == 'ok'){
                    $('#userName').text(data.result.name);
                    $('#userEmail').text(data.result.email);
                    $('#userPhone').text(data.result.phone);
                    $('#userCreated').text(data.result.created);
                    $('.user-content').slideDown();
                }else{
                    $('.user-content').slideUp();
                    alert("User not found...");
                } 
            }
        });
    });
});
</script>

PHP Script (getData.php)

This PHP script is called by the Ajax request. Based on the user ID the details are fetched from the database using PHP and MySQL. The retrieved data returns as JSON format to the Ajax.

<?php
if(!empty($_POST['user_id'])){
    
$data = array();
    
    
//database details
    
$dbHost     'localhost';
    
$dbUsername 'root';
    
$dbPassword '*****';
    
$dbName     'codexworld';
    
    
//create connection and select DB
    
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);
    if(
$db->connect_error){
        die(
"Unable to connect database: " $db->connect_error);
    }
    
    
//get user data from the database
    
$query $db->query("SELECT * FROM users WHERE id = {$_POST['user_id']}");
    
    if(
$query->num_rows 0){
        
$userData $query->fetch_assoc();
        
$data['status'] = 'ok';
        
$data['result'] = $userData;
    }else{
        
$data['status'] = 'err';
        
$data['result'] = '';
    }
    
    
//returns data as JSON format
    
echo json_encode($data);
}
?>

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

Leave a reply