Search code examples
jqueryjsonjgrowl

jquery jqrowl get message from getjson


first thing first, im a PHP developer and im trying to learn jquery (javascript) and so far ive learn a lot but im a bit lost.

json output.

{"msg": [{"message":"blah", "header":"title of blah"}, {"message":"blah", "header":"title of blah"}]}

i made it like because i wanted something like this.

$message = blah

$header = title of blah

and not

message = message

header = header

which is what im getting by using ....

$.getJSON("json.php", function(data) {
$.each(data, function(key, val) {
$.jGrowl(key, { 
life: 5000,
header: val,
});
});
});

i know, i need to add another $.each and this is where im lost a bit. i need something more like this but in javascript.

$msg = array("message" => 'blah', "header" => 'title blah' );

$message = $msg['message']; // blah
$header = $msg['header']; // title of blah

Solution

  • I'm not sure I understand it well. But you don't need 1 more "each" loop I think. Does the code below suit you ?

    $.getJSON("json.php", function(data, textStatus, jqXHR) {
      // if you only put data as input, data variable is an array like [data, textStatus, jqXHR] I think. Thus the "each" function returns you the data, the status and the xhr I think
      $.each(data.msg, function(index, value) {
        // for each entry of the msg array, create a notification. "value" is a {"header": "...", "content": "..."} object
        $.jGrowl(
          value.message, // here is the notification's content
          {
            group: "myhtmlclass",
            life: 5000,
            header: value.header, // here is the notification's title
          }
        });
      });
    });