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];
...
}
Related
I'm at a beginner level in front-end development; I'm attempting to refactor some code as a side project for myself to improve my skills. My job has a list of images targeted by their skus being dynamically added to div's. I have included the following code that I have attempted to refactor.
var getProductNavigateDetail = function(skuList) {
var postUrl = "/Browse/ProductDynamicComponent/GetProductNavigateDetailJson";
$.ajax({
url: postUrl,
type: "POST",
data: { skus: skuList },
dataType: "json",
success: function(result) {
if (result[0] != null) {
$('#a1Price').html(result[0].FormattedPrice);
$('#a1Name').html(result[0].Name);
$('#a1Link').attr('href', result[0].NavigateUrl);
$('#a1Link').attr('href', result[1].NavigateUrl);
$('#b1Price').html(result[1].FormattedPrice);
$('#b1Name').html(result[1].Name);
$('#c1Price').html(result[2].FormattedPrice);
$('#c1Name').html(result[2].Name);
$('#c1Link').attr('href', result[2].NavigateUrl);
$('#a2Price').html(result[14].FormattedPrice);
$('#a2Name').html(result[14].Name);
$('#a2Link').attr('href', result[14].NavigateUrl);
$('#b2Price').html(result[15].FormattedPrice);
$('#b2Name').html(result[15].Name);
$('#b2Link').attr('href', result[15].NavigateUrl);
$('#c2Price').html(result[16].FormattedPrice);
$('#c2Name').html(result[16].Name);
$('#c2Link').attr('href', result[16].NavigateUrl);
}
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
getProductNavigateDetail('160555,665087,159816,482743,228984,519217,320165,216235,229010,687943,332256,513663,482508,216243,330495,340218,668637,232524,414899,444139,560632,329734');
It seems pretty obvious that it just needs to iterated over with a loop so I made this code.
var getProductNavigateDetail = function(skuList) {
var postUrl = "/Browse/ProductDynamicComponent/GetProductNavigateDetailJson",
imageURL = "www.website.com/";
$.ajax({
url: postUrl,
type: "POST",
data: { skus: skuList },
dataType: "json",
success: function(result) {
if (result[0] != null) {
for (let i = 0; i < skuList.length; i++) {
$('#a' + [i] + 'Price').html(result[i].FormattedPrice);
$('#a' + [i] + 'Name').html(result[i].Name);
$('#a' + [i] + 'Link').attr('href', result[i].NavigateUrl);
$('#a' + [i] + 'Image').attr('src', imageURL + result[i].ImagePath);
}
}
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
getProductNavigateDetail('160555,665087,159816,482743,228984,519217');
Trying to figure out a way to get the implementation of the first but just using a short iteration with jQuery. Any tips, advice or scenarios to look at would be gladly appreciated!
Ok so result is the response from the AJAX request, and I'm assuming this is an array of products. such as:
[ { FormattedPrice: 'somethin', Name: 'someName' } ]
What you send as data is a comma-seperated list of SKUs ('160555,665087,159816,482743,228984,519217'). Firstly, you assume that the result you get back is in the exact same order as your comma-seperated list you sent in, and that it will always contain the same number of products as you have asked for. If any products are missing from the database, and your array is 1 less than you expect, you will get an error in your loop as your try and access that missing array entry...
Secondly, your loop is not going to implement the exact same thing as what is done in the original code (the div ID's can start with either a, b or c, and then it jumps from results[2] to results[14]). So I am unsure how you are going to target the correct div ID with only the index of the array you are looping through unless it follows a strict pattern.
So overall I'm not entirely sure what you need to achieve and it would be hard to write the code for you without seeing the full result object and your front-end HTML.
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.
I've been reading this, this, this until I reached this.
Basically what I'm trying to do is just iterate the data returned from an Ajax call which is json_encoded in the php side.
This is the structure of the object that returned when I use console.log(data):
Object {0: "218", 1: "SCT_22156", 2: "10456", 3: "S5_MAN_Artwork-Processing", 4: "Duma Guete", ID: "218", ARTICLE_ID: "SCT_22156", METADATA_ID: "10456", FROM_STAGE: "S5_MAN_Artwork-Processing", SEND_FROM: "Duma Guete"}
What I use to iterate is this (I would like to get each value from each key, so example I would like to get the metadata_id):
$.each(data, function( k, v ) {
console.log(v.METADATA_ID);
});
But this returns undefined.
Note: During ajax call data returned maybe one or more object.
What I noticed, it doesn't return undefined when the data returned is more than one object, thus making it JSONArray. So if the data returned is like this:
Object [{"data":"value"..},{"data":"value"..}]
$.each works fine.
Is there anyway that I can specifically tell the server side (php) should return JSONArray even it contains one object only?
I tried using for in loop too, but in reverse it doesn't work with JSONArray. I tried adding timeouts too, but no luck. What am I doing wrong here?
This is my ajax call:
$.ajax({
type:'POST',
url: ,
data:,
dataType : 'json',
success: function(data){
console.log(data);
if(data){
$.each(data, function( k, v ) {
console.log(v.SEND_FROM);
});
}
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
I tried using this trick:
$.each([data], function( k, v ) {
console.log(v.METADATA_ID);
});
Adding brackets,but it will cause undefined for JSONArray(multiple object) result.
If I understand correctly, you're trying to distinguish whether data is an array or a single object? If so, I'd suggest checking this post.
Since you're using jQuery you can use isArray:
$.ajax({
type:'POST',
url: ,
data:,
dataType : 'json',
success: function(data){
console.log(data);
if(data){
if ($.isArray(data))
{
for (var i = 0; i < data.length; i++)
console.log(data[i]['SEND_FROM']);
}
else
console.log(data['SEND_FROM']);
}
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
I have data in a JSON object with the following format:
[{"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}]
I've started to write some code to pull information from an API, but am not sure how to extract information (for instance, "stringforfeature3" if I somehow call "Feature 3") from the JSON object.
ajax: {
type: "GET",
url: '/api/apiname/info/moreinfo', //where i'm pulling info from
dataType: "JSON",
success: function(data, textStatus, jqXHR) {
return {
title: // Where I'd like to use the extracted information
};
}
},
Any advice would be greatly appreciated!
First of all, the response is an array, You need to get the first element like this
response = data[0];
Do you know each of the keys in advance? If yes,
{ title: response['Feature 3'] }
Else you can loop over response
for (var key in response) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + response[key]);
}
}
You should be able to extract the data using square bracket notation:
success: function(data, textStatus, jqXHR) {
return {
title: data[0]['Feature 3']
};
}
You result is an array, so I used data[0] to get the first item of array, or {"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}.
In JavaScript you can access the same variable either using object.variable or object['variable']. Since your variable name has spaces, you are left with second option - data[0]['Feature 3']. Your result will be stringforfeature3.
I don't know if this is malformed JSON string or not, but I cannot work out how to parse each result to get the data out.
This is the data.d response from my $.ajax function (it calls a WebMethod in Code Behind (C#)):
{"Row":[
{"ID1":"TBU9THLCZS","Project":"1","ID2":"Y5468ASV73","URL":"http://blah1.com","Wave":"w1","StartDate":"18/06/2015 5:46:41 AM","EndDate":"18/06/2015 5:47:24 AM","Status":"1","Check":"0"},
{"ID1":"TBU9THLCZS","Project":"2","ID2":"T7J6SHZCH","URL":"http://blah2.com","Wave":"w1","StartDate":"23/06/2015 4:35:22 AM","EndDate":"","Status":"","Check":""}
]}
With all the examples I have looked at, only one or two showed something where my 'Row' is, and the solutions were not related, such as one person had a comma after the last array.
I would be happy with some pointers if not even the straight out answer.
I have tried various combinations of response.Row, response[0], using $.each, but I just can't get it.
EDIT, this is my ajax call:
$.ajax({
url: "Mgr.aspx/ShowActivity",
type: "POST",
data: JSON.stringify({
"ID": "null"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblResErr').html('<span style="color:red;">' + thrownError);
}
});
At the moment I have just been trying to get ID1 value and ID2 value into the console.
EDIT (Resolved): Thanks to YTAM and Panagiotis !
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
data = JSON.parse(data);
console.log(data);
}
Now the console is showing me an array of two objects, and now I know what to do with them !!
First you have to parse the string with JSON.parse
var data= JSON.parse(rowData);
Then you will get object like given below,
data = {
"Row": [
{
"ID1":"TBU9THLCZS",
"Project":"1",
"ID2":"Y5468ASV73",
"URL":"http://blah1.com",
"Wave":"w1",
"StartDate":"18/06/2015 5:46:41 AM",
"EndDate":"18/06/2015 5:47:24 AM",
"Status":"1",
"Check":"0"
},
{
"ID1":"TBU9THLCZS",
"Project":"2",
"ID2":"T7J6SHZCH",
"URL":"http://blah2.com",
"Wave":"w1",
"StartDate":"23/06/2015 4:35:22 AM",
"EndDate":"",
"Status":"",
"Check":""
}
]}
Here I am giving two options either direct retrieve data from data variable or through loop.
data.row[0].ID1
data.row[0].Project
data.row[0].ID2
and so on
OR
use loop,
var result = json.row;
for (var i = 0; i < result.length; i++) {
var object = result[i];
for (property in object) {
var value = object[property];
}
}
Hope this helps.
you may be getting a json string from the web method rather than an actual JavaScript object. Parse it into a JavaScript object by
doing
var data = JSON.parse(response);
then you'll be able to iterate over data.Row