views:

77

answers:

2

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?

+1  A: 

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).

Peter Di Cecco
+1  A: 

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']);
}
});
a paid nerd