Jump to content

JQuery $.get .json


Spunky

Recommended Posts

Hi, I am attempting to get data from a .json file located on the server. Below is the code a that is not working. I know I can read from a .json file using PHP but when I learned that it can be done with JQuery I figured it would be less hassle than retrieving the data from a .php file.

 

The data on stored_houses.json was entered via PHP as a json array and it is confirmed to contain data.

 

The two alerts in the $.get function output: object Object

 

The error I get in the JavaScript console is: Uncaught TypeError: Cannot read property '0' of undefined for the 3rd alert.

var stored_houses;$.get("stored_houses.json", function(data){	alert(data);	stored_houses = data;	alert(stored_houses);});		alert(stored_houses[0].address)

Contents of stored_houses.json file:

{"location":"41.5200305, -88.20172930000001","address":"Shorewood, IL"}
Link to comment
Share on other sites

Also, the request is made asynchronously. This alert

alert(stored_houses[0].address)

will fail as it will get executed immediately (and at best introduce as race condition), so you have to do all your work with the response data within the callback function instead (like you are already doing)

Link to comment
Share on other sites

  • 3 weeks later...

Also, the request is made asynchronously. This alert

alert(stored_houses[0].address)

will fail as it will get executed immediately (and at best introduce as race condition), so you have to do all your work with the response data within the callback function instead (like you are already doing)

 

That is good to know, thank you. I will need to make sure I set the variables within the function.

 

In your case, data is just a string. To convert it to a Javascript object you can use JSON.parse().

stored_houses = JSON.parse(data);

jQuery has a method that automatically parses JSON received from a request. http://api.jquery.com/jQuery.getJSON/

 

So I ultimately got this to work sort of with the following code:

$.getJSON("stored_houses.json", function(data){  alert(data.address);});

The alert alerts the address data from the first entry of the JSON, but how do I alert data from the 2nd? data[0].address doesn't alert the same thing, instead gives an error that it is undefined.

Link to comment
Share on other sites

From you first post, you say your response is this

 

{"location":"41.5200305, -88.20172930000001","address":"Shorewood, IL"}

 

You only have an object, not an array. Array notation data[0].someProperty will return exactly what you are seeing, undefined

Link to comment
Share on other sites

{"houses": [        {"location": "41.5200305, -88.20172930000001", "address": "Shorewood, IL"},        {"location": "22.2222222, -22.22222222222222", "address": "address2, IL"},        {"location": "33.3333333, -22.22222222222222", "address": "address3, IL"}    ]}

to retrieve

            $(document).ready(function() {                $.getJSON("stored_houses.json", function(data) {                    for (i = 0; i < data.houses.length; i++)                    {                        alert(data.houses[i].location + ' ' + data.houses[i].address);                    }/* OR jQuery$.each(data.houses, function(idx, value) { alert(value.location + ' ' + value.address); //option 1//alert(data.houses[idx].location + ' ' + data.houses[idx].address); }); //option2*/                });            });
Edited by dsonesuk
Link to comment
Share on other sites

Contents of JSON file:

{"houses":[{"location":"41.5200305, -88.20172930000001","address":"Shorewood, IL"},{"location":"41.617222, -88.20277799999997","address":"Plainfield, Il"}]}

Code to retrieve:

$.getJSON("stored_houses.json", function(data){   alert(data.houses[0].address);});

Nothing happens when the code runs. No errors.

Link to comment
Share on other sites

There must be more code that you're not showing. If you put that code right between <script> tags it will work.

 

If it's inside a function, you have to make sure that the function is being called at some point.

Link to comment
Share on other sites

There must be more code that you're not showing. If you put that code right between <script> tags it will work.

 

If it's inside a function, you have to make sure that the function is being called at some point.

 

Must have been something wrong with the cache, it is working today. Thank you for your help.

Link to comment
Share on other sites

One more question though, in regards to this process.

$stored_houses = fopen("stored_houses.json","a");$store_data = array("location" => $latlng, "address" => $address);fwrite($stored_houses,json_encode($store_data));fclose($stored_houses);

This is the PHP used to save the data to the JSON file to begin with. It doesn't include the beginning or end tag stuff I had to add to make the retrieving work (including the comma between the two sets but I know that is easy enough). Would I need to retrieve the data and rewrite all of it to the file every time a new entry is added in order to include the stuff the code above does not include? Does this tedius process make using a JSON file not ideal for the purpose I am using it?

 

For example, now when I add a new entry, this is what the file looks like:

{"houses":[{"location":"41.5200305, -88.20172930000001","address":"Shorewood, IL"},{"location":"41.617222, -88.20277799999997","address":"Plainfield, Il"}]}{"location":"41.5894752, -88.057837","address":"Lockport, IL"}
Link to comment
Share on other sites

By opening the file in "a" mode you're appending new data onto the file which causes it to not be real JSON anymore.

 

This is JSON:

{"property":"value"}

This is not JSON

{"property":"value"}{"property":"value2"}

If you want to actually add more to the data, you'll have to decode the JSON, add the data, then encode it again before writing it to the file. When you do write to the file, set the file mode to "w" to overwrite what's already in the file.

 

JSON is usually dynamically generated upon request, not stored in a file. If you had a database, you would get PHP to retrieve the data from there and encode it in JSON before sending it.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...