$.each function is not iterating - javascript

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

Related

How to use jQuery forEach statement?

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

how to iterate each array element in response in $.ajax

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>');
});

assign object to array in javascript multidimensional array

Below i have given my code which is a javascript function which calls a php file and gets json data .... all things are perfect yet but i am getting problem when i want to adda data to a multidimensional array .. sorry for this noob question.. i don't know it can be done or not.
what i want to do
i want to retrieve data on ajax call and save this data to array
so i dont need to call again if i need data again
so i want to store data in multidimensional array which will have two keys
first key will be length iof array
and second will be dataType of my data which can be "name", "id", "description"
is this right way to do this
if it is not then what should i try ...? HELP ME...!!!
or can i assign full jsondata object data got from ajax call success to an array
Newly added requirements of my question
Its associative array like my php array of data is like
$data[0]["id"] = 1;
$data[0]["name"] = "spomething";
$data[0]["descriptoon"] = "spomething";
$data[0]["image"] = "spomething";
//for second item
$data[1]["id"] = 1;
$data[1]["name"] = "spomething";
$data[1]["descriptoon"] = "spomething";
$data[1]["image"] = "spomething";
so i want to create same array for javascript... for every item i fetch... from ajax../ and include into javascript array...
$('.searchButton').bind("mouseover", function() {
var data = $(this).parents('.item').attr('id');
var type = $(this).parents('.tab-pane').attr('id');
// dataArray will be global javascript variable because of its needdss... it will be outside the function
var dataArray = new Array();
$.ajax({
type: 'GET',
url: '<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success: function(data){
var dataArrayLength = dataArray.length;
dataArray.push({dataArrayLength:data});
console.log(dataArray[0]);
}
});
});
now i change my code on thebasis of your suggestion i can push data object in array via push fn ... now how do i call inside data from that object ....!
Object {dataArrayLength: Object}
dataArrayLength: Object
description: "World famous roasted Chicken, avacado, fresh mushrooms, red onions. Mozzarella cheese and our secret sauce."
id: "11"
images: "/htdocs/kiosk/images/dining/items/pizzas/11.jpg"
name: "Bella Notte Signature Pizza"
price: "4.50"
raters: "10"
ratings: "1"
__proto__: Object
__proto__: Object
this is the output of console.log(dataArray[0]) ... so now i want to get "id" , "name", "description" from it how can i do this...????/
MY SOLUTION TO PROBLEM
success:function(data){
var dataArrayLength = dataArray.length;
dataArray.push(data);
dataArray.forEach(function(object,index){
console.log(object.id);
console.log(object.name);
console.log(object.description);
console.log(object.image);
console.log(object.ratings);
});
and this is what i want to do ...
Try this:
$.ajax({
type:'GET',
url:'<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success:function(data){
dataArray = []; // empty it before pushing data into it...
dataArray.push(data);
}
});
I believe you can directly push the data object into the dataArray.
and while you access this simple access it like dataArray[i].id, dataArray[i].name and so on for all the keys of data.
I'm not quite sure i understand, but cant you simply do:
$.ajax({
type:'GET',
url:'<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success:function(data){
var dataArrayLength = dataArray.length;
dataArray.push({'id':data.id,'name':data.name,'image':data.image,'description':data.description});
}
});
});
Or even:
dataArray.push(data);
I havent tested this so consider it pseudo code but i belive that the push method is what you are looking for?

Unable to post Javascript array via jQuery ajax

I am extremely reluctant to ask this question as I know it is something really stupid I am missing, but I simply cannot get this to work. Code below:
<script>
var formArray = new Array();
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";
$('#my_button').click(function() {
$.ajax({
type: "POST",
url: "scheduler.php",
data: formArray,
success: function(response){
console.log(response);
}
});
});
</script>
Server side PHP Script scheduler.php
<?php
print_r($_POST);
?>
All I get back logged to the console is an empty array:
Array
(
)
If I console.log formArray within the click function it shows the complete array just fine. So why is it not posting it to my PHP file?
Thanks in advance
Changing Array() to Object() would work as well.
You would get:
Array
(
[start] => one
[stopat] => two
[stop_at] => three
)
You are adding string properties to an array, which is for storing numeric indices.
Use an object instead:
var formArray = {};
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";
jQuery will iterate over the indices in an array, using a for (var i = 0; i < formArray.length; ++i) loop, which will completely miss any properties you've added to the array.
Also, new Array should have been [] (as {} should be preferred over new Object). Don't use the new X method of initialization for built-in types. (Crockford, The Good Parts)
JavaScript Arrays are designed to hold an ordered sequence of items with integer keys. When jQuery converts a data structure into Form URL Encoded data and encounters an array, it will iterate over those integer keys and not over named keys.
Use an Object if you want to have named keys.
Change new Array() to newObject()
Edit your Ajax like this and see if it works: data: {data: formArray}, dataType: 'JSON'
$.ajax({
type: "POST",
url: "scheduler.php",
data: {data : formArray},
dataType: 'JSON'
success: function(response){
console.log(response);
}
});
PHP:
print_r($_POST['data']);

How to Access Array response of AJAX

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

Categories

Resources