Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to parse JSON array in jQuery?
    primarykey
    data
    text
    <p><strong>EDIT</strong> I checked the jQuery documentation and using $.ajax with the json datatype specified returns an evaluated javascript object, so eval() isn't the answer here. I knew that anyway, since I am able to parse single JSON objects, just not arrays. The problem is the $.each-ing my way through them :)</p> <p>I have followed the syntax for parsing a JSON array in jQuery to the letter, but it doesn't work for some reason. I am fetching the array using $.ajax, have specified the correct datatype, and in Firebug can see that the response from my PHP script is []. Yet when I try to use $.each to iterate through the array, all I get is undefined values when I try to console.log various parts of the array. Here is where my php script makes and encodes the array:</p> <pre><code>if(mysqli_num_rows($new_res) &gt; 0) { $messages = array(); while($message_data = mysqli_fetch_assoc($query_res)) { $message = array( 'poster' =&gt; $message_data['poster'], 'message' =&gt; $message_data['message'], 'time' =&gt; $message_data['time'] ); $messages[] = $message; } echo json_encode($messages); } else if(mysqli_num_rows($new_res) == 0) { $message = array( 'poster' =&gt; '', 'message' =&gt; 'No messages!', 'time' =&gt; 1 ); echo json_encode($message); } </code></pre> <p>And here is my attempt to parse it:</p> <pre><code> var logged_in = '&lt;?php echo $logged_in; ?&gt;'; var poster = '&lt;?php echo $_SESSION["poster"];?&gt;'; $.ajax({ url: 'do_chat.php5', type: 'post', data: ({'poster':poster,'logged_in':logged_in}), dataType: 'json', success: function(data) { $.each(data, function(messageIndex, message) { console.log(parseInt($('#chatWindow :last-child &gt; span').html())+' '+message['time']); if((parseInt(message['time']) &gt; parseInt($('#chatWindow :last-child &gt; span').html()))) { $('#chatWindow').append('&lt;div class="poster"&gt;'+message['poster']+'&lt;/div&gt;&lt;div class="message"&gt;&lt;span&gt;'+message['time']+'&lt;/span&gt;'+message['message']+'&lt;/div&gt;'); } }); } }); </code></pre> <p>Without the $.each function I am able to successfully parse single JSON objects, but not an array. This is my first outing with JSON and $.each, and I'm pretty new to jQuery, so go easy if my code has ugly bits!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload