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

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.

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

How to retrieve java Set and iterate over the values from response of ajax call?

I have following ajax call
$.ajax({
type: "GET",
url: "../targeturl",
data : postdata,
contentType: 'application/json',
success: function(response, status, request) {
** in response im getting three sets which i wish to iterate
}
last few lines of controller methods are as follows:
JsonWrapper response = new JsonWrapper();
/*some lines to fetch data from db*/
response.addParam("vSet",vSet);
response.addParam("dSet",dSet);
return response;
Since I have never tried this before, please tell me know how to perform this. also let me know if question is not clear enough.
Using JQuery :
$.each(response.vSet, function(index, element) {
//process
});
Using Javascript :
for(var i=0;i<response.vSet.length;i++){
//process
}
If your response is valid Json, you can parse the response using javascripts built in function JSON.parse(). Then iterate over it as you like, depending on how you constructed your json in your response.
$.ajax({
type: "GET",
url: "../targeturl",
data : postdata,
contentType: 'application/json',
success: function(response, status, request) {
var json = JSON.parse(response).
//iterate over json by accessing the indices of json.
for(var i = 0; i < json.length; i++)
{
(..) //do stuff with json[i]
}
//or access json using the key values you specified in your response
json['vSet'] // or json.vSet.
console.log(json) //this will allow you to inspect your response after you parsed it to json.
}

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()

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

Javascript: Trouble parsing json response

Spring is returning a json-encoded object with four properties. One of which is a property named "array". I want the contents of this array.
Here's the whole json response:
ee
{"map":null,"array":[{"id":2,"description":"Cloud For Dev","businessSize":2,"businessType":9,"businessLocation":3},{"id":3,"description":"Cloud For Prod","businessSize":2,"businessType":9,"businessLocation":3}],"string":null,"bool":false}
0
I'm not actually sure what the "ee" or 0 mean... Anyway, I'm trying to parse it like this:
$.ajax({
type: "GET",
url: "/ajax/rest/teamService/list",
dataType: "json",
success: function (response) {
var teamArray = response.array;
var $el = $("#teamSelect");
$el.empty();
$.each(teamArray[0], function(team) {
alert(team.description);
$el.append($("<option></option>").attr("value", team.id).text(team.description));
});
// Reattach the plugin
$("#teamSelect").selectbox("detach");
$("#teamSelect").selectbox("attach");
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus === 'error') {
setTimeout(function() { window.location = '/do/login'; }, 7000);
}
}
});
And I'm getting the alert box pop up 6 times (should be 2), and each time it says "undefined" rather than the actual description.
The select box itself has four empty options.
Seems like I'm iterating over the json encoded object's four parameters, NOT the two contents of the enclosed array.
How can I fix this?
Try this - teamArray[0] should be only teamArray
$.each(teamArray, function(i,team) {
alert(team.description);
$el.append($("<option></option>").attr("value", team.id).text(team.description));
});
Right now, you're looping over the keys of teamArray[0], hence the six alerts. Loop over teamArray. Also, $.each's callback takes indexInArray, valueOfElement. May as well not jQuery through that:
for(var i = 0; i < teamArray.length; i++) {
var team = teamArray[i];
...
}

Categories

Resources