Use localStorage to hold ajax response and then use as object - javascript

Hi have the following Ajax request that gets JSON from the server and stores the json in localStorage for which I can use in my application. It seems like my code to accomplish this is not efficient at all, but I cant get it to work any other way. I have tried storing as an object, but it seems to want to be stored as a string.
Is there a better way to do this?
//GET Users List from Server
function getUsersList() {
$.ajax({
url: "api/ListUsers",
dataType: "json",
success: function (e) {
localStorage.UsersList = (JSON.stringify(e));
var usersList = localStorage.UsersList;
var usersList = $.parseJSON(usersList)
console.log(usersList[0])
}
});
}

You can only store strings in the localStorage, however you could create an abstraction of the serialization/deserialization process in a reusable function.
Have a look at Storing Objects in HTML5 localStorage
Also, it's recommended to use the setItem and getItem methods.

Related

How to pass a JavaScript array as parameter to URL and catch it in PHP?

I have an array in JS and I am trying to pass it as parameter to URL and catch it in PHP but I cant get to understand how to do it:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
FYI: I am using windows.fetch for posting.
in PHP:
$trafficFilters = $_GET["trafficFilters"];
$obj = json_decode($trafficFilters);
var_dump($obj);
You are passing the data to php with fetch() intead of ajax, so the alternative of my first answer to do the same with the fetch() is:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var trafficFilterHolderJoin = trafficFilterHolder.join(); // comma-separeted format => "roadworks,snow,blocking"
Now add the trafficFilterHolderJoin variable to the traffic query of the URL of your fetch(), like:
fetch('script.php?traffic=' + trafficFilterHolderJoin)
Then in your php script file you will convert the comma-separeted format to php array format using the explode function:
$traffic = explode(",", $_GET['traffic']);
It's quite simple, you are passing these data to php with ajax, correct?
First of all, you are creating the javascript array incorrectly:
var trafficFilterHolder = [0: "roadworks", 1: "snow", 2: "blocking"];
Don't use brackets to create arrays with keys, use this format instead:
var trafficFilterHolder = {0: "roadworks", 1: "snow", 2: "blocking"};
Now, in the ajax, just add the array in the data:
$.ajax({
data: { trafficFilters: trafficFilterHolder }
});
All demands to the server are executed as an http requests. Ther are two types of HTTP requests - GET and POST.
https://www.w3schools.com/tags/ref_httpmethods.asp
What you're describing is called GET request. With GET request the parameters are passed via the address bar. For making an http request you have two options.
The direct HTTP GET request.
For this you need simply open a new page with
window.location.href = 'http://your_site.com/file.php?name1=value1&name2=value2'
This will open a new page in your browser and pass a request with your parameters.
An Ajax HTTP GET request.
You have a lot of options here:
an old-fashion way with xmlHttpRequest object
a modern fetch API with promises
third-part libraries like jQuery.ajax etc.
AJAX request can send and receive information from the server (either in GET or POST request) without renewing the page. After that the result received can be managed with your javascript application however you want.
Hope, it makes more clear for you. You can search about all this technologies in the google. This is the way how to exchange data from front-end to back-end.
Try using ajax and pass that array and retrieve values at the PHP end.
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
$.ajax({
type: "POST",
url: "test.php",
data: {data : filters},
cache: false,
success: function(){
alert("OK");
}
});

Saving json data in a URL to browser memory on page load

I have a URL which contain some data in JSON format. I want to save this data in local browser memory on page load. Later I need to use this local copy as a source for my JQuery autocomplete. At the moment I'm pointing autocomplete source to this URL, so its calling that service very frequently.
Please help me to save the data in browser local memory and how to use it for jQuery autocomple.
Thank you.
If you really want to store it locally more permanently take a look at local storage
You should be able to do something like
$(document).ready(function {
$.get('http://example.com', function (data) {
localStorage.setItem('autocomplete', data.toString());
});
And then on any page you can use
var autocompleteData = JSON.parse(localStorage.getItem('autocomplete')
$('#myautocomplete').autocomplete({source: autocompleteData});
But it may simply be good enough just to declare a page scope variable and use that. That way it calls once per page load and you don't need to expire it.
<script>
var autocompleteSource;
$(document).ready(function {
$.get('http://example.com', function (data) {
autocompleteSource = JSON.parse(data);
});
$('#myautocomplete').autocomplete({source: autocompleteSource});
});
</script>
This assumes that you can parse the response into an array in the appropriate format.
Update based on comment:
I think you will still need to pass in the function as the source, as you are doing a contains search (indexOf(..) != -1).
Your autocompleteSource would contain all of the nested data: perhaps
$.get('http://example.com', function (data) {
autocompleteSource = [];
data.countries.map(function(itemCountry) {
itemCountry.cities.map(function(itemCity) {
itemCity.destinations.map(function(itemDestination {
autocompleteSource.push(itemDestination);
});
and then you would declare the method just working off the local data set
$('#myautocomplete').autocomplete(source : function (request, response){
var filtered = autocompleteSource.filter(function(item){
return item.toLowerCase().indexOf(request.term.toLowerCase()) > -1
});
response(filtered);
});

Assigning JSON object to variable from google sheets URL?

I want to be able to pull data from a google spreadsheet doc every 24hrs and use the values in my html page.
I have managed to get the JSON url for the cell I want to track, but I do not know how to get this JSON object into a javascript variable using the url.
I have searched around and tried using Jquery $.get() and $.getJSON() but I cant seem to get anything to work.
The url for the google spreadsheet data cell JSON is
https://spreadsheets.google.com/feeds/cells/1r56MJc7DVUVSkQ-cYdonqdSGXh5x8nRum4dIGMN89j0/1/public/values/R29C4?alt=json-in-script&callback=importGSS
I know this is probably simple but I am very new to working with JSON/ Javascript and have been struggling to work this out.
Thanks for any help :)
The data being returned is jsonp so you need to specify that in your Ajax request.
function getData() {
return $.ajax({
url: 'https://spreadsheets.google.com/feeds/cells/1r56MJc7DVUVSkQ-cYdonqdSGXh5x8nRum4dIGMN89j0/1/public/values/R29C4?alt=json-in-script&callback=importGSS',
dataType: 'jsonp',
jsonpCallback: 'importGSS'
})
}
And while you can assign the data to, say, a global variable this will only get you so far - the Ajax process is asynchronous and you won't be able to access the data until the process has finished:
var obj;
getData().done(function (data) {
obj = data;
});
// console.log(obj) here will return undefined as the process
// has not yet finished
Much better to grab the data and do something with it:
function doSomethingWithData(data) {
console.log(data);
}
getData().done(function (data) {
doSomethingWithData(data);
});
Or even simpler:
getData().done(doSomethingWithData);

How can I iterate this json?

"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there

How do I append more data to an AngularJS model?

So far I'm having no issue setting up an AngularJS model in my Rails application and giving it data to access on the front-end. I even set it up to be populated with data from an AJAX request using $http. However, I need this this model to contain the data of multiple $http calls. Here's the code I've got thus far:
function DropboxCtrl($scope, $http) {
var $infiniteLoader = $(".infiniteLoader");
var theUIDS = $infiniteLoader.attr('data-dropbox-uids').split(',');
if($infiniteLoader.attr('data-dropbox-uids') != "") {
var theData = {};
$.each(theUIDS, function(key) {
$http({ url: '/dropbox/files/get', method: 'GET', params: { uid: theUIDS[key] }}).success(function(data) {
theData = data;
});
});
$scope.dropboxes = theData;
}
}
I have a method called DropboxCtrl which will start by getting all the UID's that I need to call a GET request on. I loop through each of them and then append data to theData which is a Javascript object. After the each I make my dropboxes model equal to the value of theData. Current I've got the method returning absolutely nothing and no Javascript errors. I am positive that my url works completely and actually did get the code working with just one AJAX request like such:
$.each(theUIDS, function(key) {
$http({ url: '/dropbox/files/get', method: 'GET', params: { uid: theUIDS[key] }}).success(function(data) {
$scope.dropboxes = data;
});
});
However... that code block only returns the last AJAX call because the other ones are overwritten. Maybe what I'm missing is just incorrect Javascript, however, maybe what I'm missing is just a lack of understanding the "Angular way" of things. I'm skilled in Javascript and jQuery, but very new to Angular. Any help?
AngularJs is a high level Javascript framework. The code ultimately is javascript. Within your $each, you can push results to an array or to an initialized collection like
$scope.dropboxes = [{uid:1234}, {uid:2345}] and so on.
within the $each, locate the record for uid and attach the results.
I usually use underscorejs library for operations on collections, arrays etc.
so something like
_.findWhere($scope.dropboxes, {uid: data.uid }).data = data;
assuming the data that is returned has uid in it. If not then there should be another way to map the results to the request. Note that there is no guarantee of the order of responses, so you cannot use array indexes to map results.

Categories

Resources