AJAX请求返回null

I have the following PHP:

<?php

 $get_messages = mysqli_query($mysqli, "SELECT * FROM messages");

 $messages = array();

 while ( $row = mysqli_fetch_array($get_messages)){

      $messages[] = array( 'name' => $row['name'], 'message' => $row['message']);
 }

 $json = json_encode($messages);
 echo $json;

?>

Which successfully echo the following JSON:

     [{"name":"Ernest","message":"hello"},{"name":"Ernest","message":"hello"},{"name":"john","message":"yes"},{"name":"Diana","message":"I know
"},{"name":"fgafg","message":"fgehfegfvg"},{"name":"fgafg","message":"fgehfegfvg"},{"name":"fgafg","message":"fgehfegfvg"},{"name":"gsfvgx","message":"fbhfxvcz"},{"name":"argttrhjyrbsgdzdc","message":"ahjtgfrdcvdfsevb"}] 

Then I have this JS:

$(document).ready(function(){

  $.ajax({
     url: 'retrieve.php',
     dataType: 'json',
     success: function (response) {
       alert(response[3]);
     }
   });
});

which alerts undefined.

What is the issue here ? Your help will be appreciated.

NOTE: If I change the alert to alert(response[3].name); or alert(response[3][name]); the alert window does not even show up to the party

response is an array of items with name and message properties. So you should basically loop through the items and access it.

You need to make sure that your ajax call is hitting the success handler. May be add an error handler to verify it.

success: function (response) {

   $.each(response,function(a,b){
     alert(b.name);
     alert(b.message);
   });       

 },
 error : function(a,b,c){
    alert("error");
    alert(c);
 }

Here is a working sample of iterating the array.

Also, If there are any other script error in your page, it won't work. So make sure you don't have any other script error. You can verify it by checking your browser console.

Try:

$.ajax({
                type: "POST",
                data: {
                    message: JSON.stringify(message)
                },
                url: "retrieve.php",
                success: function(message) {
                        alert(message);
                }
            });