1

I'm new to jquery and JSON. I have the following JSON structure.

{
   "address":{
      "suburb":[
         "HACKHAM WEST",
         "HUNTFIELD HEIGHTS",
         "ONKAPARINGA HILLS",
         "m"
      ],
      "state":"SA"
   }
}

So basically the above is the response from this:

$.ajax({
    type:'POST',
    url: 'getAddress.php',
    data:postCode='+postCode',
    success: function(response) {
        alert(response)
    }
});

So, what I'm trying to get is a variable containing state, and an array containing the suburbs.

1
  • Your data is wrong in your $.ajax. It should be data: 'postCode='+postCode, Commented Jun 26, 2012 at 17:43

3 Answers 3

5

Check you have valid Ajax request:

$.ajax({
    type: "POST",
    url: "getAddress.php",
    data: {
        postCode : postCode          // data as object is preferrable
    },
    dataType: "json",                // to parse response as JSON automatically
    success: function(response) {
        var state = response.address.state;
        var suburbs = response.address.suburb;
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

I see.. So, I need the dataType to be 'json'? Thanks
@user933791 If you expect the server to return json, you mightaswell specify json as the datatype. If you return proper headers from the server jQuery might detect that it as json, but it is usually better to specify it.
@user933791 Yep. Otherwise, getAddress.php should send the following content type in header: header("Content-Type: application/json");.
3

This should do the trick

$.ajax({type:'POST', 
    url: 'getAddress.php', 
    dataType: 'json',
    data:'postCode='+postCode, 
    success: function(response) {
        var state = response.address.state;
        var suburbs = response.address.suburb;   
    }
});

Added dataType:'json' and fixed the data parameter.

Comments

1

You need to parse the JSON you get. $.ajax can do this for you.

$.ajax({
    type:'POST',
    url: 'getAddress.php',
    data: 'postCode='+postCode, // make sure this line is correct
    dataType: 'json', // this tells jQuery to parse it for you
    success: function(response) {
        var state = response.address.state;
        var suburbs = response.address.suburb;
    }
});

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.