skip to Main Content

I have a GET form that gets a Php Array and json encodes it. The Issue I am having is the success data is not displaying. I want the success to display data in a Alert or console but for some reason it’s not working. I have tried many options. Thanks for your help.

PS: I know the GET and all files work because when I got the script the Ajax response result would populate/append a table successfully. I am modifying it.

Here is the php index file with the AJAX:

<!doctype html>
<html>
<head>
    <title>Return JSON response from AJAX using jQuery and PHP</title>
    <link href="style.css" type="text/css" rel="stylesheet">
    <script src="jquery-3.1.1.min.js" type="text/javascript"></script>
</head>
<body>
        
<script>        
 $(document).ready(function() {
    $.ajax({
        url: 'ajaxfile.php',
        type: 'get',
        dataType: 'JSON',
        success: function(data) {
            var obj = jQuery.parseJSON(data);
            alert(obj.username);
        }
    });
});
</script>  
</body>
</html>

Here is the php file that queries the database and encodes/array json:

<?php

$return_arr = array();

$sql = "SELECT * FROM users  ORDER BY NAME";
$result = $conn->query($sql);


// Check database connection first
if ($conn->query($sql) === FALSE) {
    echo 'database connection failed';
    die();
} else {
    while($row = $result->fetch_array()) {
        $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);
}
?>

echo json_encode array output from the php file looks like below (test content):

[{"id":"1","username":"jiten","name":"Jiten singht","email":"jiten9"},{"id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldee"},{"id":"3","username":"mayank","name":"Mayank","email":"mayank"},{"id":"9","username":"mohit","name":"Mohit","email":"mohit"},{"id":"13","username":"mukesh","name":"Mukesh","email":"mukesh"},{"id":"6","username":"nitin","name":"Nitin","email":"niti"},{"id":"12","username":"palash","name":"Palash","email":"palash"},{"id":"7","username":"rahul","name":"Rahul singh","email":"rahul"},{"id":"10","username":"rohit","name":"Rohit singh","email":"rohit"},{"id":"8","username":"shreya","name":"Shreya","email":"shreyam"},{"id":"11","username":"sonarika","name":"Sonarika","email":"sonarika"},{"id":"5","username":"vijay","name":"Vijay","email":"vijayec"},{"id":"14","username":"vishal","name":"Vishal Sahut","email":"visha"},{"id":"4","username":"yssyogesh","name":"Yogesh singh","email":"yoges"}]

when I make the success result (data) and alert(data), this is what I get,empty objects

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution tested and working. To echo/alert Json_encoded php Array in Ajax you need to add "JSON.stringify(data)" inside the alert brackets as below.

    <script>        
     $(document).ready(function(){
        $.ajax({
            url: 'ajaxfile.php',
            type: 'get',
            dataType: 'JSON',
            success: function(data){
             alert(JSON.stringify(data));
              
    
            }
        });
    });
    
    </script>  
    

  2. Try iterating on array of objects after success: function

        $(document).ready(function () {
            $.ajax({
                url: 'ajaxfile.php',
                type: 'get',
                dataType: 'JSON',
                success: function (data) {
                    var results = JSON.parse(data);
                    let output = "";
                    $.each(results, function (key, value) {
                        output += value.id + " " + value.username + " " + value.name + " " + value.email;
                    });
    
                    alert(output);
                }
            });
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search