Charbel Obeidi
Charbel Obeidi

Reputation: 21

$.each is looping over each character in my json and displaying undefined

i need to loop over the below json but the below code is looping over each character in my json and displaying "undefined": (is there anything wrong with the below json??? Any help is appreciated)

{"news_id":"1","news_title":"News Title One","news_date":"2012-03-20","news_pic":"album-bb[6].jpg","news_desc":"Here goes the news title one Here goes the news title one Here goes the news title one Here goes the news title one.","gallid":"3"}
{"news_id":"2","news_title":"News Title Two","news_date":"2012-04-14","news_pic":"174863_163190093755777_2032987021_q.jpg","news_desc":"News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two.","gallid":"0"}

This is my code which is being fired on click event:

var phpNews;
var NewsObject;

$(document).ready(function () {

    $("#btnNewsPage").click(function()
    {
        $.post("server/news.php",null,function(e){
            NewsObject = e;
            $.mobile.changePage("#NewsPage");
        });
    });

    $('#NewsPage').live('pagebeforeshow',function(event, ui){
        var list;
        $.each(NewsObject, function(k,v){
            list = v.news_title;
        });

        $("#displayNews").html(list);
    });

})

Upvotes: 0

Views: 191

Answers (1)

gakhov
gakhov

Reputation: 1971

Looks like, your NewsObject isn't a JSON object but string. It could happen because JQuery can't guess the response type, so you, probably, need to specify dataType for your $.post request (documentation):

$.post("server/news.php", null, function(e){ ... }, 'json');

P.S. Also your JSON not looks valid, i expect to see something like {'a':'b'}, but you have {'a':'b'} {'c':'d'}.

Updated. Based on the comments below, i would suggest you to use next PHP code for your server/news.php:

<?php 

require "../includes/config.php"; 
require "../includes/h.conn.php"; 
require "../includes/admin.id.php"; 

$strSQL = "select * from news where admin_id=" .$admin_id; 
$objRS = mysql_query($strSQL);
$News_Obj = array();

while ($row = mysql_fetch_assoc($objRS)) {
    $record = array (
               "news_id" => $row['news_id'], 
               "news_title" => $row['news_title'], 
               "news_date" => $row['news_date']
    );
    $News_Obj[] = $record; 
}

// don't forget to clear after yourself: mysql_free_result, disconnect

header("Content-type: application/json");
echo json_encode($News_Obj);
?>

Also you can use Firebug to see what exactly returns the script and which HTTP or Javascript errors happen when you do a request.

Upvotes: 2

Related Questions