johnnyb
johnnyb

Reputation: 139

when using JSON/AJAX where exactly is this data getting sent to and how do I then access it?

this is a total beginner question. My question is about data that you can send to the server using $.get or $.getJSON or $.ajax (or other methods). I don't understand where this data is actually stored or how to access it.

Let's say I have a file called test.json, that looks like this:

{
"name":"Bob",
"age":"84",
"sex":"male"
}

I want to display this data in an alert, as well as send new data to the server using $.getJSON, like so:

$(function() {
$.getJSON("ajax/test.json",{height:"tall",shoes:"sneakers"},
  function(data) {
      alert("Data Loaded:" +data.name);
  });
});

So the alert will display "Bob". However, if change the alert to ("Data Loaded:" +data.height); the alert will say "undefined". So this is a basic concept I'm not getting - where exactly is this data getting sent to and how do I then access it?

Upvotes: 2

Views: 190

Answers (2)

barfoon
barfoon

Reputation: 28177

height isn't defined in your json file, so when you call ("Data Loaded:" +data.height);, it really doesn't have anything to return.

In your code, you calling a get type method that is returning the data in test.json. Height isnt in there, so when you go to go print it out, it is undefined.

Upvotes: 1

pleonasm
pleonasm

Reputation: 66

The second argument to $.getJSON() are parameters to be passed along with the URL. In your case, the URL that will be requested from the server is

GET {REST_OF_URL}ajax/test.json?height=tall&shoes=sneakers

Where {REST_OF_URL} is which URL the javascript is downloaded from.

If you want to be able to get back height and shoes in your response object, you would need to have the server dynamically add those values to the JSON object before it's returned to the browser with whatever server side language you have available.

Upvotes: 0

Related Questions