First thing, the simple response which I get back from $.ajax is this:
http://pastebin.com/eEE72ySk
I am using this code:
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
var result = JSON.parse(data);
$('#responsestatus').text(result.Response.ResponseStatus);
});
I was trying this code:
$.each(result.Response.Results[0][0].AirlineRemark, function (i, item) {
$("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
});
When I use the above code, then error is:
Uncaught TypeError: Cannot use 'in' operator to search for '5' in IndiGo
When I tried this code without the forEach loop :
$("#divResult1").text(result.Response.Results[0][0].AirlineRemark);
I get no error but the output is only the first one. Indigo is showing however in response there are 20 arrays in Results. I have shown only two arrays in result in the link provided above.
Please someone tell me how to iterate each and every item in results array.
AirlineRemark is not an Array, so looping through that one is not possible. So loop through the array of arrays, and find the property within each loop
$.each(result.Response.Results[0], function (i, item) {
$("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
});
You're trying to iterate a non-array there. If, result is based on your JSON that you provided. This is one way you can iterate it,
// Each items in result.Response.Results
$.each(result.Response.Results, function(i, items) {
// Get the AirlineRemark at the item at 0 index.
var airlineRemark = items[0].AirlineRemark;
// Append it to #divResult1
$("#divResult1").append('<p>' + airlineRemark + '</p>');
});
Beware that on sample above, items is an array. And it will only get the first item.
You can try this
$.each(result.Response.Results, function () {
$("#divResult1").append('<p>'+this[0].AirlineRemark+'</p>');
});
Related
Note please. (I'm currently using the Spring Framework (MVC))
The value sent from Controller to ajax is ...
It looks like the picture above.
I am looping through the forEach statement for the values in that array, and I want to put the value into the tag.
So I wrote the code.
$(function()
{
$('#doctorSelect').change(function()
{
$('#selectGugan').show();
var doctor_idx = $(this).val();
$.ajax
({
type: 'POST',
url: 'selectDoctor.do',
data: {"d_idx":doctor_idx},
dataType: 'JSON',
success: function(sectionDate)
{
console.log(sectionDate);
var html = "<option value=''>Choice Doctor</option>";
var responseData = [];
responseData.push(sectionDate);
console.log(responseData);
$.each(responseData, function(key, value)
{
console.log("forEach statement in responseData :" + responseData);
//html+="<option value="+new_date+">"+new_date+"</option>";
});
$('#doctorSelect_2').html(html);
},
error: function(sectionDate)
{
console.log("data : " + sectionDate);
}
});
});
});
But unexpectedly, I do not get the key, value.
In fact, I don t know about the jquery forEach statement.
How do I set key, value?
I just want to bring those values and express it like this.
<option value="ri_idx">ri_startDate ~ ri_endDate</option>
How to set key, value or How to use jquery forEach statement ?
I am a beginner. I would appreciate it if you could give me an example.
In your case I am not sure why would you be doing this:
responseData.push(sectionData);
because this way you dont get an array of objects as I believe you thought you would, you simply will get an array with 1 element in it, which is many objects, so doing a forEach on that array will not help, because the value will be the multiobject element (not a single object that you could access properties).
What you want to do is iterate over your original objects, so your code should be something like this:
$.each(sectionDate, function(key, value){
// here you can access all the properties just by typing either value.propertyName or value["propertyName"]
// example: value.ri_idx; value.ri_startDate; value.ri_endDate;
});
Hope this helps!
In jQuery forEach working like this
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
If you are using Array for loop than key is array index and value values and if you are using javascript object then object key is key and value is object value for the particular key.
You can read more at jQuery documentation.
Just use property names in object. Check if this helps
$(document).ready(function() {
var responseData = [
{startdate: '2017-12-21', enddate: '2017-12-22', idx: '1'},
{startdate: '2017-11-21', enddate: '2017-11-22', idx: '1'},
{startdate: '2017-10-21', enddate: '2017-10-22', idx: '1'}
];
var html = '';
$.each(responseData, function(key, value) {
html += "<option value=" + value.startdate + ">" + value.startdate + "</option>";
});
$('#doctorSelect').html(html);
});
I am working with a relatively complex JSON structure and am unable to iterate through it via the $.each() function. I'm pretty sure it's something to do with the weird 2-dimensional array I am passing through in the value section of the normal array (hope that made sense). I am new to Ajax and JSON so just need some guidance on the best way to handle JSON when it is returned via an AJAX Call. Thanks!
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var i = 0;
for(var k in data){
window.alert(k);
} //this works
$.each(data, function(key, value){ //however this does not display anything
window.alert("should be outputted");
window.alert("key" + key + "value" + value[i]['email']);
i++;
});
});
JSON I am using:
{"bodge.com":[{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},{"email":"fwzqfjma#bodge.com","orders":"3","value":"13.71"},{"email":"rwsofs#bodge.com","orders":"7","value":"6.49"},{"email":"vfr#bodge.com","orders":"3","value":"24.36"},{"email":"wcs#bodge.com","orders":"3","value":"11.26"},{"email":"oqmsboag#bodge.com","orders":"3","value":"5.36"},{"email":"wdvm#bodge.com","orders":"6","value":"18.21"},{"email":"xubumenme#bodge.com","orders":"1","value":"10.24"},{"email":"pleqlwpha#bodge.com","orders":"2","value":"6.59"},{"email":"dqhdcnvw#bodge.com","orders":"10","value":"7.85"},{"email":"gyxymze#bodge.com","orders":"1","value":"15.51"},{"email":"otbbqcw#bodge.com","orders":"2","value":"7.92"},{"email":"afspqpq#bodge.com","orders":"3","value":"13.22"},{"email":"fwovyddw#bodge.com","orders":"4","value":"23.14"},{"email":"urczmgy#bodge.com","orders":"7","value":"15.17"},{"email":"hkgccna#bodge.com","orders":"4","value":"17.62"},{"email":"hlrnunyf#bodge.com","orders":"4","value":"22.03"},{"email":"gafoubu#bodge.com","orders":"10","value":"16.71"},{"email":"muwfjqs#bodge.com","orders":"4","value":"6.09"},{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},{"email":"jbq#bodge.com","orders":"8","value":"5.37"}],"bodge.com ":[{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}]}
Your JSON has (at least) two levels:
an object with keys ("bodge.com", "bodge.com "), and
each key holds an array of objects
{
"bodge.com": [
{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},
{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},
...
{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},
{"email":"jbq#bodge.com","orders":"8","value":"5.37"}
],
"bodge.com ": [
{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}
]
}
In order to iterate through the structure, you will need at least two levels of iteration:
$.each(data, function(domain, objects) {
console.log(domain); // will output "bodge.com" or "bodge.com "
$.each(objects, function(index, x) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
Note that you are using $.each for two different kinds of iteration: first over the keys and values of an object, then over the items in an array.
As an alternative, use Object.keys to get an array of an object's keys, and the forEach method:
Object.keys(data).forEach(function(domain) {
console.log(domain); // will output "bodge.com" or "bodge.com "
data[domain].forEach(function(x, index) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
It looks like you should be bypassing data['bodge.com'] into the each function rather that simply data.
You could try this;
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var list = JSON.parse(data);
$.each(list, function(i){
alert(list[i].your_filed);
});
});
I'm struggling with a issue populating a DropDown menu with an array.
My array, stored in an external json files is in the following format :
[{"name":"value_A", "other":"value_A1"}, {"name":"value_B1"}, {"name":"value_C"} ]
In order to use these data, I first push them in a array, then try to push them in a drop down menu.
My jQuery looks like the foolwoing :
function loadData() {
$.getJSON(database, function (data) {
for(var i=0; i<data.length; i++) {
myNewArray.push(
{
"name":data[i].name
})
$.each(data, function(i, item) {
$("#myDiv").append('<option>' + data[i].name + '</option>')
});
};
});
}
It works "well" as dat go to my drop down menu, but it iterate all the data as the same amount of object.
For example, I f I got 10 objets in my array, it return 10 times the whole values asked
How to "stop" the iteration after query deliver the selected
[{"name":"value_A", "other":"value_A1"}, {"name":"value_B"}, {"name":"value_C"} ]
will return in a console :
value_A
value_B
value_C
value_A
value_B
value_C
value_A
value_B
value_C
I think I'm not so far for the good code, but after testing lot of combination, I can't solve it withou your help.
Thanks for any advise on this.
You have a $.each() inside a for loop, so it creates a double iteration causing same elements to be added multiple times.
Only one of $.each() or the for loop is required
function loadData() {
$.getJSON(database, function (data) {
$.each(data, function (i, item) {
myNewArray.push({
"name": item.name
})
$("#myDiv").append('<option>' + item.name + '</option>')
});
});
}
I'm new to jQuery. Following is the data variable that contains a json dictionary.
{
"user":null,
"currency":"EUR",
"balance":0,
"translist": [
{ "trans1":"something","trans2":"something2" }
]
}
and my jQuery method receives a json/Javascript object from the Rest GET call
success: function (data){
for(x in data) {
console.log(x + ': ' + data[x]);
}
});
Is there any library that can help to parse/walk through this json object and get to some kind of objects list? I want to check some of the keys and their respective values. Problem is I don't need all the keys and values from the list and also some of the values can be null, which prevented me to apply some solutions I found using SO.
Or usually is it more common to directly start printing the HTML inside the success function?
EDIT:If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some array list with the values I want from it. What's equivalent of that in jQuery?
If it was java for example it would be a Map and I would use an
iterator to walk through and see/analyse the map values, and create
some arraylist with the values I want in it. What is the equivalent of that
in jQuery?
Any javascript object can be seen as an associative map.
You can for example directly access the currency as data['currency'].
You can also build an array :
var a = [];
for (var key in data) {
a.push({key:key, value:data[key]});
}
You could also build some HTML and apply functions to the data :
$(document.body).append($(
'<table>' + a.map(function(v){
return '<tr><td>'+v.key+'</td><td>'+v.value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Using jQuery can make the same iteration simpler (working directly from data) :
$(document.body).append($(
'<table>' + $.map(data, function(value,key){
return '<tr><td>'+key+'</td><td>'+value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Try using each
success: function (data){
$.each( data, function( key, value ) {
if(key === "currency")
alert( key + ": " + value );
});
});
This is my AJAX call response which is in array format
[1,2,3,4,5,6]
success: function(outputfromserver) {
$.each(outputfromserver, function(index, el)
{
});
How can we access outputfromserver all values ??
Means outputfromserver Zeroth value is 1 , 2nd element is 2 , -----so on
It would help to know what your AJAX request looks like. I recommend using $.ajax() and specifying the dataType as JSON, or using $.getJSON().
Here is an example that demonstrates $.ajax() and shows you how to access the returned values in an array.
$.ajax({
url: 'test.json', // returns "[1,2,3,4,5,6]"
dataType: 'json', // jQuery will parse the response as JSON
success: function (outputfromserver) {
// outputfromserver is an array in this case
// just access it like one
alert(outputfromserver[0]); // alert the 0th value
// let's iterate through the returned values
// for loops are good for that, $.each() is fine too
// but unnecessary here
for (var i = 0; i < outputfromserver.length; i++) {
// outputfromserver[i] can be used to get each value
}
}
});
Now, if you insist on using $.each, the following will work for the success option.
success: function (outputfromserver) {
$.each(outputfromserver, function(index, el) {
// index is your 0-based array index
// el is your value
// for example
alert("element at " + index + ": " + el); // will alert each value
});
}
Feel free to ask any questions!
The array is a valid JSON string, you need to parse it using JSON parser.
success: function(outputfromserver) {
var data = JSON.parse(outputfromserver);
$.each(data, function(index, el) {
// Do your stuff
});
},
...
You can use JS objects like arrays
For example this way:
// Loop through all values in outputfromserver
for (var index in outputfromserver) {
// Show value in alert dialog:
alert( outputfromserver[index] );
}
This way you can get values at first dimension of array,
above for..loop will get values like this:
// Sample values in array, case: Indexed array
outputfromserver[0];
outputfromserver[1];
outputfromserver[2];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
However, when implemented this way, by using for ( index in array ) we not only grab indexed 1,2,3,4,... keys but also values associated with named index:
// Sample values in array, case: accosiated/mixed array
outputfromserver["name"];
outputfromserver["phone"];
outputfromserver[37];
outputfromserver[37];
outputfromserver["myindex"];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
In short, array can contain indexed values and/or name associated values, that does not matter, every value in array is still processed.
If you are using multidimensional stuff
then you can add nested for (...) loops or make recursive function to loop through all and every value.
Multidimensional will be something like this:
// Sample values in array, case: indexed multidimensional array
outputfromserver[0][0];
outputfromserver[0][1];
outputfromserver[1][0];
outputfromserver[1][...];
outputfromserver[...][...];
Update, JSON object:
If you server returns JSON encoded string you can convert it to javascript object this way:
try {
// Try to convert JSON string with jQuery:
serveroutputobject = $.parseJSON(outputfromserver);
} catch (e) {
// Conversion failed, result is not JSON encoded string
serveroutputobject = null;
}
// Check if object converted successfully:
if ( serveroutputobject !== null ) {
// Loop through all values in outputfromserver
for (var index in serveroutputobject) {
// Append value inside <div id="results">:
$('#results').append( serveroutputobject[index] + "<br/>" );
}
}
// In my own projects I also use this part if server can return normal text too:
// This way if server returned array we parse it and if server returns text we display it.
else {
$('#results').html( outputfromserver );
}
More information here
$.ajax({
type : "POST",
dataType: "json",
url : url,
data:dataString,
success: function(return_data,textStatus) {
temperature.innerText=return_data.temp;
// OR
**temperature.innerText=return_data['temp'];**
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error while accessing api [ "+url+"<br>"+textStatus+","+errorThrown+" ]"); return false;
}
});