Mansa
Mansa

Reputation: 2325

Get specific data from jQuery JSON into variable

I have tried almost everything, but can't figure this out?

I am creating a list view for my HTML app using JSON and this part was working just fine. But in the same JSON call I want to be able to send other data as well I can put into some variables but am unsuccessfull.

Here is what I am trying:

dataUrl = 'http://mypage.com/playermenu.php?callback=?&userid=' + userid,
dataCallback = function(data){
    //var content = data.list.join("");
    //var now = data.menutime; // HERE I WANT THE MENUTIME TO BE PUT INTO A VARIABLE //
    alert("Date: "+data.menutime);
    $('#userbar').html(data.profile); // FETCHING USERS DATA FOR PROFILEBAR //
    $('#games').html(content).listview('refresh');
}

$.getJSON(dataUrl, dataCallback);

The above alert gives: Date: undefined

My JSON looks like this:

([{"menutime":"2013-04-28 15:00:50"},{"profile":"troels"}])

Hoping for help with this.

Thanks in advance :-)

Upvotes: 1

Views: 187

Answers (1)

Michael Geary
Michael Geary

Reputation: 28850

Why is the server adding the ()? That makes it invalid JSON, which is rejected by $.getJSON().

Take a look at the JavaScript console in your browser. It should have an error something like this:

SyntaxError: Unexpected token (

Is this your own server code? If so, you should fix it to produce valid JSON.

If you are stuck with using this invalid JSON format, then you should use $.get() or $.ajax() instead of $.getJSON() and specify "text" format:

$.get( dataUrl, dataCallback, 'text' );

Now your callback function will receive the bad JSON as plain text. So at the top of dataCallback you can remove the superfluous parentheses and parse the remaining JSON data:

var data = $.parseJSON( data.match( /^\((.*)\)$/ )[1] );

Upvotes: 1

Related Questions