Get data from localStorage with ajax - javascript

I have an array that consists of some links, this array is stored in localStorage. I have a page where I want to display all of them. So when I append any item to my array, it has to be added to the page using ajax.
I have a function that just creates this table using data from local storage:
function get_table(links) {
let result = ["<table class='table text-center'>"];
let number = recent.length;
result.push("<thead><tr><th scope='col'>Page Number</th><th scope='col'>Link</th></tr></thead>")
result.push("<tbody>")
for(let link of links) {
result.push(`<tr><td>${number}</td><td>${link}</td></tr>`);
number--;
}
result.push("</tbody></table>");
return result.join('\n');
}
But I don't know where to apply ajax. I tried doing so:
$.ajax({
type: "POST",
url: "http://127.0.0.1:8000",
data: {recent: localStorage.getItem('RecentPages')},
dataType: 'json',
success: function(data)
{
$('.container').append(get_table(data));
},
});
But it doesn't work. How can I achieve my goal?

There's an approach to add your new data to the table without re write it. I was looking for a callback or event to get when Array.push happen but there isn't.
function ArrayEvent(array){
this.Array = array;
this.push = function(data){
//push the data in the array
this.Array.push(data);
//store it in the local storage
localStorage.setItem("links", JSON.stringify(this.Array));
//add to the end of the table
$("table.table > tbody").append(`<tr><td>${data.number}</td><td>${data.link}</td></tr>`);
};
}
If you don't like it, you could also try with Proxy:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Related

JSON objects wont transfer into js array using ajax

I get undefined when i try to console.log it
var farr = [];
$.ajax({
url: "https://whispering-cliffs-33347.herokuapp.com/employees",
type: "GET",
contentType: "application/jsonp"
}).done(function(employees) {
for(let i in employees){
farr.push(employees[i]);
}
})
console.log(farr[8]);
Any ideas?
console.log(farr[8]); will be executed even before the response is available.So in first done push all the elements in the local array & once that is done in the next done log the value
var farr = [];
$.ajax({
url: "https://whispering-cliffs-33347.herokuapp.com/employees",
type: "GET",
contentType: "application/jsonp"
}).done(function(employees) {
employees.forEach(function(item){
farr.push(item)
})
}).done(function(elem){
console.log(farr[8]);
})
You can not iterate the object with standard for loop. To be able to do that, you should first get object keys in an array and iterate over that.
const keys = Object.keys(employees);
keys.forEach((i) => {
farr.push(employees[i]);
}
console.log(farr[8]);. // You should put this in the call back itself
Or you can directly iterate over the object using lodash's forEach.

How to find the length of Success Data in Jquery Ajax?

I am retrieving list from ajax, when it become success, I wants to add those list values to DropDownList Items, So I want to iterate the data until last value and then add it to DropDownList
Here is my code What i tried
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "GPCreateCheque.aspx/getOpenRequestNo",
dataType: "json",
success: function (data) {
alert(data.length);
for (var i = 0; i<data.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
},
error: function (result) {
alert("Error");
}
})
In alert box it is showing undefined
UPDATE
I return the list<string> from [webmethod]
use data.d.length
alert(data.d.length);
for (var i = 0; i<data.d.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
You need to do data = JSON.parse(data); before treating your data like an array. It's just a string up to that point.
Update: if your data is not the array itself, but instead an object that contains an array named d, you need to work with that. It depends on your data structure.
Check the response from network tab in Chrome Developer Console or similar tool. May be response code is 200 but response data is missing.
On the other hand you want to itarete data in for loop but you try to append data.d[i]. If you want to append data.d[i] you have to itarete data.d in for loop.

From an ajax json request, how can dynamically add the objects to an array so that I can loop through them?

This is what I have so far, essentially I'd like to use the data to instantiate a new info-window from google maps api dynamically from the data response. I know so far that I'm pushing objects to an array(which are two different data types), but if that's the only wrong here. Then how can I dynamically add the response into an object so I can retrieve data with a loop?
var i, venues, allVenues=[];
$.ajax({
url: 'url',
dataType: 'json',
data: 'data'
async: true,
success: function(data) {
venues = data['response']['groups'][0]['items'];
JSON.parse(venues);
for(i in venues){
allVenues.push(venues[i]);
}
};
/*Do something realistic with data other than logging it to console*/
console.log(allVenues);
You do it right, but not in the right place. jQuery.ajax will not wait for the response, but will invoke a 'success' callback when the request is answered.
Try this:
var i, venues, allVenues=[];
$.ajax({
url: 'url',
dataType: 'json',
data: 'data'
async: true,
success: function(data) {
venues = data['response']['groups'][0]['items'];
// The following line of code does nothing, because you
// did not store it's return value. Fortunately it wasn't
// even needed
//
// JSON.parse(venues);
for(i in venues) {
allVenues.push(venues[i]);
}
// or
// allVenues.push.apply(allVenues, venues);
// or in ES6
// allVenues.push(...venues);
// or the following will create a new array instance and save it in the allVenues variable
// allVenues = allVenues.concat(venues);
/*Do something realistic with data other than logging it to console*/
console.log("Here are your updated venues:");
console.log(allVenues);
}
});
console.log("These are your old venues:");
console.log(allVenues);
EDIT:
You can check that the identity of the allVenues array didn't change by printing it to the console every second:
setInterval(function(stored) {
console.log(stored);
console.log(stored === allVenues);
}, 1000, allVenues);
EDIT:
To update an array to contain only the items of another array, you can use:
allVenues.length = 0;
allVenues.push.apply(allVenues, venues);
or
allVenues.length = venues.length;
for (var i in venues) {
allVenues[i] = venues[i];
}

Creating divs in AJAX loop

I am getting data from the server side using AJAX, I am now trying to populate data from from a list of objects into divs, the problem I am having is that I can not create the div while inside of the foreach loop.
$(document).ready(function () {
var divs = "";
var url = "../Graphs/CreateChart";
$.ajax({
type: 'POST',
url: url,
success: function (data) {
for (var i in data) {
var x = data[i];
for (var j in x) {
var val;
if (x.hasOwnProperty(j)) {
val = x[j].SpName;
if (x[j].SpName != "undefined") {
$('#a').appendTo('#content');
createBarChart("#a", "USP_Charts_BarChart1");
}
}
}
}
}, dataType: "json",
cache: false
});
});
</script>
I am trying to populate where it says "#a" with val and also then I need to populate the div I write with the val for the id, but when I try to put the document.write inside of the loop, I get a blank screen, any ideas why it would do this?
you're trying to append a created variable to your content? Try making the markup a string FIRST then appending it.
To test it try it without data.
$("<h2>HI</h2>").appendTo("#content");
If that works, then make a string that is the markup you want, with the data you need.
$("<a data='"+data.variable+"'></a>").appendTo("#content");
append and appendTo are VERY similar, but you need to use a string, not just an identifier, if the object doesn't exist yet.

Sorting value fetched by jquery ajax call into javascript multidimensional array

I'd like to store a value that is correctly fetched via (NON ASYNC) ajax call (from facebook graph api) back to my javascript multidimensional array.
Everything works fine until the part when the data that I get from facebook api has to be stored to my previously defined 2d-array (and afterwards printed on the page via jquery append). I simply can't figure out where's the problem.
Here's the code sample:
Defining 2d array and its values:
fbpages = new Array (13);
i=0;
for (i=0;i<=12;i++) fbpages[i]=new Array(4);
fbpages[0][0] = "http://graph.facebook.com/120830347930692?callback=?";
fbpages[0][1] = "Kupi";
fbpages[0][2] = "/vijesti/tag/kupi/";
fbpages[0][3] = 0;
fbpages[1][0] = "http://graph.facebook.com/214014840762?callback=?";
fbpages[1][1] = "Kolek";
fbpages[1][2] = "/vijesti/tag/kolek/";
fbpages[1][3] = 0;
etc...
Fetch the data for every page using the URL from the array fbpages[x][0] and store it back to the same array, to the field fbpages[x][3]:
y=0;
for (y=0;y<=12;y++){
pageURL = fbpages[y][0];
fetchData(y,pageURL);
};
function fetchData (index,fbpageurl) {
$.ajax({
type: "GET",
url: fbpageurl,
dataType: "json",
async: false,
success:function(data){fbpages[index][3]=data.likes;}
});
};
Data printing works fine.
Thanks in advance!

Categories

Resources