jQuery .each loop not looping but does when you console.log? - javascript

little confused, i have a .each function which displays all results from JSON when i use console.log but when i try to output using .html() it only shows one? any reason why?
code:
$(document).ready(function(){
$.get('functions/ListOrders.php', function(xml){
var newOrders = $.xml2json(xml);
$.each(newOrders.ListOrdersResult.Orders.Order, function(index, value) {
//console.log(value.AmazonOrderId);
$('#orderAmount').html("<b>Order Total:</b><br>" + index + "<br><br>");
$('#orderListing').html("<b>Order Listing:</b><br>" + value.AmazonOrderId);
});
});
});
Thanks

You getting only one result because in your loop you override existing value. Basically you override html value. If you use append instead it will add values to your existing elements with each loop iteration.
$(document).ready(function(){
$.get('functions/ListOrders.php', function(xml){
var newOrders = $.xml2json(xml);
$.each(newOrders.ListOrdersResult.Orders.Order, function(index, value) {
$('#orderAmount').append("<b>Order Total:</b><br>" + index + "<br><br>");
$('#orderListing').append("<b>Order Listing:</b><br>" + value.AmazonOrderId);
});
});
});

Related

Access data from Object in json response

My json returns below shown set of array of objects and I need to access the data inside it. In the console this is what the response looks like
What i am trying to do is to access the object to get the subcategoryid and subcategoryname then display it inside a dropdown list. Here is my code for it
$.get('ajax-subcat?cat_id=' + cat_id, function(data)
{
console.log(data);
$('#subcategory').empty();
$.each(data, function(index, subcatObj)
{
alert(subcatObj);
$('#subcategory').append('<option value="' + subcatObj.Object.subcategoryid +'">' + subcatObj.subcategoryname +'</option>');
});
});
The thing I don't know is how to access the data inside the object. Any ideas?
Try this:
JAVASCRIPT
for (var i = 0; i < data.length; i++) {
console.log(data[i].subcategoryid);
}
Assuming that you have a select element in markup:
<select id="mySelectElement"></select>
Try this to iterate the object and fill the combo box:
$.get('ajax-subcat?cat_id=' + cat_id, function(data) {
// Get a reference to the target element
var selectTarget = $('#mySelectElement');
// Iterate over the response data
for (var i in data) {
// For every object in array, append a new option element
selectTarget.append($('<option value="' + data[i].subcategoryid + '">' + data[i].subcategoryname + '</option>'));
}
});
For this purpose, you can use underscore.js library to get whole data corresponding to particular key in the form of array.
_.pluck(data, 'subCategoryid') // array of all values corresponding to 'subcategoryid'

Jquery binding loop variable to getJSON function

I have a for loop that GETs a json array and populates it in a table along with another list's variables. My problem is I am not able to access i inside the get method. But I have mylist and all its contents inside. I tried binding the function to a variable i using bind(this,i) but that says .getJSON() is not a function. Here's the relevant code.
var mylist = ["a", "b", "c"]
for (i = 0; i < mylist.length; i++) {
urlstr = "/" + mylist[i]; // Generate url
$.getJSON(urlstr, function(data) {
html = "<tr><td>" + mylist[i] + "</td><td>" + data.string[0] + "</td></tr>";
$("#tableresult").append(html); //this returns undefined for mylist[i]
console.log(i); //this returns 3 which is the length of list
});
}
In short I need the variables outside getJSON be accessible within getJSON.
Can someone please help? Thanks and regards.
This should be no different from binding the loop variable in practically any other loop. Since you are working with an array, the cleanest approach is to use Array#forEach:
var mylist = ["a", "b", "c"];
mylist.forEach(function (item) {
var urlstr = "/" + item;
$.getJSON(urlstr, function(data){
var html = "<tr><td>" + item + "</td><td>" +
data.string[0] + "</td></tr>";
$("#tableresult").append(html);
console.log(item);
});
});
please ensure your php return data is json.
for example:
$data['something'] = 'data';
echo json_encode($data);
and using function for get index (i):
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});

Use html() as append()

I want to use html() same as how it works with append()
function showResponse(response) {
var $list = $('#list');
var items = response.items;
$.each(items, function(id, el){
$list.html('el.id.videoId')
});
}
I dont know if anyone did understand it but what i want is
List1 = id1, id2 id3
List2 = id4 id5 id6
When List1 is listed, and List2 will be requested this must remove List1 and list List2
With append it makes the list just longer, but i want it to replace it with current
jQuery's html() replaces all the content every time you call it, so you're replacing the content on every iteration.
To only replace the content after the loop has completed you can do
function showResponse(response) {
var $list = $('#list');
var items = response.items;
var result = "";
$.each(items, function(id, el){
result += el.id.videoId;
});
$list.html(result);
}
Try this:
$list.html($list.html() + 'el.id.videoId');
jQuery.html() returns the current html in object
jQuery.html( data ) sets object html to data
Not sure why you want to use html() when append will do the job.
Empty the list it and append the new elements
$list.empty();
$.each(items, function(id, el){
$list.append("<li>" + id + "</li>");
});
If you want to use html(), than build a string with all the list items and set it at once.
Have you tried?
$list.empty().append('el.id.videoId');

Add text with a specific class to dropdown <select>

I want to
Get Text From Classes with class .pick and populate them into a dropdown #pingList
1) my Variable picker returns a long string, so I assume I need to create an array
2) var array I want the result to be ['x','y','z'] as I assume this is what I need in the next step.
3) I then want to add this to the dropdown with the text and val set.
I am pretty sure all I am missing is the array part. Looking for some help.
My Jquery Code and Live Demo http://jsfiddle.net/UUY5Z/1/
// Get text from Pick CLass
var picker = $('.pick').text();
// Make an Array from string result above
var array = //??
// Add this to the dropdown
$.each(array, function (val, text) {
$('#pingList').append($('<option></option>').val(val).html(text));
});
.text() method returns textContent of all of the selected elements as one string, you can use .map() method instead which returns an array:
var picker = $('.pick').map(function(i, elem) {
return "<option value='"+i+"'>" +
(elem.textContent || elem.innerText) + // == $(elem).text()
"</option>";
}).get(); // array of options (string)
$('#pingList').append(picker);
http://jsfiddle.net/JJsRd/
Here an other solution , using $.each() :
$.each($('.pick'),function(i, elem){
$('#pingList').append( "<option value='"+i+"'>"+ $(elem).text() +"</option>");
});
DEMO HERE
$('.pick').each(function(){
$('#pinglist').append(""+$(this).text()+"");
});
This should work for Above Case.
http://jsfiddle.net/sushilbharwani/uNpND/
I have updated in your demo page.. #http://jsfiddle.net/UUY5Z/7/
$(".pick").each(function(){
var val = $(this).text();
$('<option>').val(val).text(val).appendTo('#pingList');
});
You can achieve the same like this.
No need to make an array.
$.each($('.pick'), function (val, text) {
$('#pingList').append($('<option></option>').val($(this).text()).html($(this).text()));
});
JSFiddle For Same http://jsfiddle.net/sushilbharwani/uNpND/

simple jquery loop through JSON array?

i have this simple jquery script to loop through JSON array
the script is not working at it all and never give output.
im sure that the JSON array is valid but i don't know why Jquery not parsing it .
$(document).ready(function(){
var cost = [{"gold":"100","iron":"80","wood":"120","food":"70"},{"gold":"80","iron":"60","wood":"90","food":"35"}];
var costarr = $.parseJSON(cost);
$.each(costarr, function(i, item) {
alert(item.gold);
}
});
You don't need to parse it, it's already an array. And your each lacks a closing )
$.each(cost, function(i, item) {
alert(item.gold);
}); //<-- lacking ")"
You have a syntax error.
$.each(costarr, function(i, item) {
alert(item.gold);
}
is missing the ending ');'
which is why nothing is being alerted in your fiddle.

Categories

Resources