JSON objects wont transfer into js array using ajax - javascript

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.

Related

Get data from localStorage with ajax

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

I mess up JSON object, arrays and strings

So i´m, trying send data from php to js.
PHP
$balkTypes[] = $stmt->fetchAll();
echo json_encode($balkTypes);
JS
balkTypesData = {}; //Outside Ajaxcall
success: function(result){
balkTypesData = result;
Console.log(balkTypesData);
}
Console
[[{"id":"3","typ":"Bas 200*600","hojd":"200","bredd":"600","rec":"","viktM":"135"},{"id":"2","typ":"Bas 240*600","hojd":"240","bredd":"600","rec":"","viktM":"160"},{"id":"5","typ":"Isol\u00e4tt 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"4","typ":"Kontur 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"6","typ":"Passbit","hojd":"0","bredd":"0","rec":"","viktM":"0"}]]
Now, i´d like to search my Json object?!
I´d like to find "viktM" for "typ:Bas 200*600"
//Get balkType weight/m
var searchField = "typ";
var searchVal = "Bas 200*600";
for (var i=0 ; i < balkTypesData.length ; i++){
if (balkTypesData[i][searchField] == searchVal) {
weigth = balkTypesData[i]['viktM'];
console.log(weigth);
}
}
First of all, it seams that i cannot use .lengton "balkTypsData". it gives me 410 hits. Must be all characters?
Second, i cannot find how to access part of my object.
If i use: console.log(balkTypesData[i][searchField]);
I get: "Undefined"
I have also tried to remove the "[i].
So what am i missing?
Be gentle i´m still learning.
Take a look at $.parseJSON() (jQuery) or JSON.parse() (vanilla):
With jQuery
success: function(result){
balkTypesData = $.parseJSON(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
Without jQuery
success: function(result){
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
When you receive the data from your AJAX request it's not JSON, just a string.
The length result that you're getting is the length of the string, not the amount of elements within the array.
Furthermore you're setting $balkTypes[] which means that you're trying to add 1 entry in the array of $balkTypes however $stmt->fetchAll(); also returns an array so you now have a nested array which is not needed.
In your PHP file change
$balkTypes[] = $stmt->fetchAll()
to
$balkTypes = $stmt->fetchAll()
this will make sure that when you fetch your data it will be an array containing all objects instead of an array containing the array of objects.
Then in your JS, instead of trying to directly read from the string, use JSON.parse() to convert the json string into a collection of JS objects/integers/arrays/strings/booleans
e.g.
success: function(result) {
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
}
EDIT
As pointed out by Armen you could also set the dataType: 'json' in the AJAX request, when the AJAX request returns it will automatically do the JSON.parse() so you can just directly console.log(result); to see the output.
Within the console.log you should now see the nested structure instead of just the string.
From here on your loop which checks the values seems correct and I would not change it unless it tells you that something is wrong.
Docs: JSON.parse();
Set in your jQuery $.ajax request additional attribute dataType: 'json'
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: { params },
success: function( response )
{
// Your data will be already json no need to parse it
console.log(response);
}
});
You are encoding a JSON on the PHP side. You are not decoding it on the JS side.
You should look at JSON.parse()

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

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];
}

json to javascript array and storing for outside ajax call use

Hey was hoping for some quick help,
My overall goal is to retrieve a php array and store it into a javascript array using an ajax call. I am new to all of this, so please bear with me.
My ajax call is successful such that it returns the echo json_encode(array); and goes to the success function.
I am confused on how to take json encoded data and store it into a javascript array that I am able to use outside the ajax call.
$.ajax({
type: "POST",
url: myurl.php
data: {var1: var1, var2:var2},
dataType: "json",
success: function(data)
{
console.log(data);
var simplified = JSON.stringify(data);
console.log(simplified);
var jsonObj = $.parseJSON('[' + simplified + ']');
},
});
The console logs gives me;
Object {63: Object, 64: Object, 65: Object}
and
{"63":{"Comment":"tc 1"},"64":{"Comment":"tc 2"},"65":{"Comment":"tc 3"}}
respectively.
I would like an array in this form;
63
Comment=>"tc 1"
64
Comment=>"tc 2"
65
Comment=>"tc 3"
Thanks for any sort of help!
UPADTE:
Any suggestions on how I would access the created array outside of the ajax call? Everytime I try to, it says it is undefined.
You have to iterate through the object's property and create an array:
var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};
var array = $.map(myObj, function(value, index) {
return [value];
});
console.log(array);
Here you are:
var data = JSON.parse('{"63":{"Comment":"tc 1"},"64":{"Comment":"tc 2"},"65":{"Comment":"tc 3"}}');
alert(data[63].Comment); // to access
Hope this help.
Your data variable is already an object. jQuery internally parsed the JSON into an object. If you want to make it an array, here you go:
$.ajax({
type: "POST",
url: myurl.php
data: {var1: var1, var2:var2},
dataType: "json",
success: function(data)
{
var arr = [];
$.map(data, function(value) {
arr.push(value);
});
}
});
But if you still need the key (you had on server-side) just keep it like that and access it like data[63]. Javascript doesn't have associative arrays, here they are objects, semanticaly called array-like objects.

Categories

Resources