Why alert (json [0] .subject); give undefined?

I have this code:

<script> $(document).ready(function() { refresh(); }); function refresh() { $.get('getMessageDetails.php', function (json) { alert(json); alert(json[0].subject); },"json"); window.setTimeout(refresh,30000); } </script> 

then I have getMessageDetails.php:

 <?php //header('Content-Type: application/json; charset=utf-8'); include('header_application.php'); $lastNewMessageCnt = $obj_clean->getUnopenedMessagesCount($_SESSION['user_id']) + 1; $last_unopened_message_row = $obj_clean->getLastUnopenedMessage($_SESSION['user_id'],$lastNewMessageCnt); echo json_encode($last_unopened_message_row); ?> 

then I have a warning (json) that shows:

 [{"subject":"Freechat ddd","id":"19","created_at":"2011-08-29 14:58:27","unique_code":"ALLEYCA000RC","opened_once":"0"}] 

what is true

but alert(json[0].subject); gives undefined

please, help? thanks

+4
source share
3 answers

If your first warning shows what you are saying, then the contents of your json variable are not treated as json - if you saw [object Object] in the warning. Check here .

So you need to indicate that json is returned (what you are doing); but you must also make sure that PHP sends the correct response headers. Add the first line below before sending the output:

 header('Content-type: application/json'); echo json_encode($last_unopened_message_row); 
0
source

You need to convert the json variable to adjust the json format variable.

There is currently a string variable.

You should use it as follows:

 <script> $(document).ready(function() { refresh(); }); function refresh() { $.get('getMessageDetails.php', function (json) { alert(json); // this is a string variable. json = $.parseJSON(json); //now json varible is in correct json format. alert(json.subject); //you can call it dirctly like a associative array. No need to include '[0]'. },"json"); window.setTimeout(refresh,30000); } </script> 
+1
source

It seems your JSON is not getting the correct analysis. Use getJSON instead.

 $.getJSON('getMessageDetails.php', function (json) { alert(json); alert(json[0].subject); }); 
+1
source

Source: https://habr.com/ru/post/1369490/


All Articles