Reputation: 77
I'm working on a Phonegap app using jQuery Mobile to download a JSON file about server statuses and for testing purposes I'm using a JSON file saved into the local folder structure.
I'm able to read the file and display it's data easily using the jQuery $.getJSON
function but I'm unsure as to how to save that data back into the file using the $.post
jQuery function.
$.getJSON("js/servers.json")
Works to get the JSON data perfectly (js/servers.json is stored in the local file structure) but when I try $.post("js/servers.json", jsonServerObj)
where jsonServerObj is the JSON I got using $.getJSON
the data doesn't seem to be saving to the file properly on page reload.
My get Function:
$.getJSON("js/servers.json").success(function (data)
{
jsonServerObj = data;
// Do stuff with data
});
And my post Function:
JSON.stringify(jsonServerObj);
$.post("js/servers.json", jsonServerObj).success(function ()
{
alert("Data sent!");
})
.error(function ()
{
alert("UH OH ERROR!");
});
jsonServerObj is set as a global variable for the JS file and the post function is returning the success alert each time,but when the page is reloaded, the JSON is not what should have been saved.
For reference, I'm testing this on an Android HTC One running Android 4.3
Upvotes: 1
Views: 3083
Reputation: 77
Here's my solution to my own problem, based on comments:
Ok, so it isn't possible to post to a local file as mentioned by some of the comments, but by using localStorage and JSON.stringify
and JSON.parse
as suggested, the data can still be stored locally like so:
function getServerData()
{
$.getJSON("js/servers.json").success(function (data)
{
// Add JSON to localStorage under serverData
localStorage.setItem("serverData", JSON.stringify(data));
// Do stuff
}
}
When retrieving, I found that you have to first retrieve the data, then parse it back into a JSON object like so:
function retrieveData()
{
var temp = localStrage.getItem("serverData");
var jsonData = JSON.parse(temp);
// Do stuff with JSON data
}
Also, I learned that localStorage data for a Phonegap application is persistent as long as the app is installed on the device, even if it is closed or stopped manually by the user.
I'm also checking to see if the data already exists via this if/else statement:
if (typeof (Storage) != "undefined")
{
if (!localStorage.getItem("serverData"))
{
alert("setting server data");
// Ajax JSON to get server information
getServerData();
}
else
{
retrieveData();
}
}
else
{
alert("localStorage unavailable!");
}
This statement will usually return true for both ifs unless the app is being opened for the first time after install. I would not recommend using localStorage for any JSON data coming from a non-local web service if that data is likely to be changed by something other than the inputs from this application, as this is only a proof of concept for an application I am prototyping.
Upvotes: 2