Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript alert from JSON response

I'm trying to build an app that gets data from server with getJSON and then alerts the row. This is the code I use but it doesn't show the row from JSON, it just says "undefined". What could be the reason for this?

$(document).ready(function(){

  $("button").click(function(){
    $.getJSON("MyURL/test.php",function(result){
      $.each(result, function(i, field){
        alert(field.MESSAGE);
      });
    });
  });
});

This is the JSON response:

{"key":[{"message":"test"}]}
like image 786
user1358625 Avatar asked Jul 21 '26 11:07

user1358625


1 Answers

result isn't an array. result.key is an array. Also your field's property is message, not MESSAGE:

$.each(result.key, function(i, field){
    alert(field.message);
});
like image 131
Paul Avatar answered Jul 22 '26 23:07

Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!