0

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?

2 Answers 2

2

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']);
}
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.