Chris
Chris

Reputation: 8836

Parsing json in jquery

I have a php file somejson.php that echos a json encoded array

{"jsonone":"first json","jsontwo":"second json"}

I'm trying to access the response with jquery ajax to use this data outside the score of the ajax call. It keeps giving me all kinds of object(Object) or undefined errors.

I'm guessing it's something as easy as wrong syntax, but it's bugging me I thought I'd ask

var mydata = {};
$.ajax({
    url: 'somejson.php',
    async: false,
    dataType: 'json',
    success: function (json) {
           mydata = json;
           mydata[jsonone] = json.jsonone;
           mydata[jsontwo] = json.jsontwo;
           alert(json[jsonone] . json[jsontwo]);           
           alert(mydata[jsontwo] . mydata[jsontwo]);    
  }
});  

//later will do some stuff with mydata jsonone and jsontwo

What are all the things I'm doing wrong here?

Upvotes: 0

Views: 621

Answers (2)

a paid nerd
a paid nerd

Reputation: 31562

Yep, simple syntax errors :-)

You need to put quotes around your hash keys and use the '+' operator to concatenate strings:

var mydata = {};
$.ajax({
    url: 'somejson.php',
    async: false,
    dataType: 'json',
    success: function (json) {
        mydata = json;
        mydata['jsonone'] = json.jsonone;
        mydata['jsontwo'] = json.jsontwo;
        alert(json['jsonone'] + json['jsontwo']);
        alert(mydata['jsontwo'] + mydata['jsontwo']);
}
});

Upvotes: 2

Peter Di Cecco
Peter Di Cecco

Reputation: 1578

I think your problem comes from the dots in your alert statements.

String concatenation in javascript is done using + not . like in php.

alert(json['jsonone'] + json['jsontwo']);
alert(mydata['jsontwo'] + mydata['jsontwo']);

Also, the array indexes should be strings (enclose in single or double quotes).

Upvotes: 1

Related Questions