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 + " ");
});
});
Related
Question
How can i set up a working example of of these planes.
Background
I have the first part working, so it seems that perhaps my loop is off? I can at least pull the number of planes. But having a problem displaying all the planes.
Here is my Demo on CodePen
I am looking at the documentation from https://developers.wargaming.net/reference/all/wowp/encyclopedia/planes/?application_id=demo&r_realm=eu
but they don't have a fully functioning example. I want to show the name of the plane, country, and show a large image. I can style it later but need a working example to help me understand and get started.
Code
API
I am pulling data from https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo
JSON output
HTML
<p>There are a total of <span id="planeQuantity"></span> planes in the database.</p>
<ul id="planes"></ul>
jQuery from
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js
Javascript
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
var name = data.id.name_i8n;
var nation = data.id.nation;
var lrgImg = data.id.images.large;
$(data).each(function(){
console.log($(this).id);
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
})
I adjusted your code a bit. Some comments:
your data.data is a Object. so, you can use for (key in object) for each key iteration (you can use jQuery's each too, but this is a pure JS approach);
name_i8n is, actually, name_i18n;
put all your var = name, var = nation and var = lrgImg into inside the loop.
Final code:
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
for (key in data.data) {
var item = data.data[key];
var name = item.name_i18n;
var nation = item.nation;
var lrgImg = item.images.large;
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
}
})
Working pen: http://codepen.io/mrlew/pen/vgaexb
Edited with some explanation
You received a data Object that have a data key whose value is a huge Object with this structure (more or less):
{
"7290": { /* ... */ },
"7291": {
"name_i18n": "North American FJ-1 Fury",
"nation":"usa",
"images":{
"large":"http://worldofwarplanes....png",
/* ... */
},
/* ... */
},
"7292": { /* ... */ }
}
So, to iterate over all keys of data.data keys we can use for (key in data.data) { }.
In each iteration, key variable will be assigned to a object key: 7290, 7291, 7292. So, to access it's value, we use data.data[key] (will be data.data["7291"], for instance), and assigned the variable item with the value.
Using brackets like this is one way in JavaScript to retrieve a value from an Object. Another way is to use dot notation (but you can't use dot notation with a key that's a number).
This is valid:
data["data"]["7291"]
This is invalid:
data.data.7291
You should set the values of name, nation and lrgImg inside each. So the elements you append won't all have the same thing. And you should loop through the data object that is inside your data object (data.data). Like this:
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
$.each(data.data, function(key, value){
var name = value.name_i18n; // get the name of this data entry
var nation = value.nation; // get the nation of this data entry
var lrgImg = value.images.large; // ...
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
});
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/? application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
$.each(data.data, function(i, e) {
var name = e.name_i18n;
var nation = e.nation;
var lrgImg = e.images.large;
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
});
You need to iterate through data.data object. Since you aren't working with dom nodes use $.each() instead of $.fn.each()
$.each(data.data, function(key, obj){
console.log(key) // "4101"
console.log(obj.name) // "type=91"
})
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'
I'm fine with using javascript or jquery
I added in another column from the database table to get returned and what I currently see is
122461,4876192
As now I have 2 records
So with that is shows
$.each(alldata.Data, function (index, query) {
strData += "<td>" + query + "</td>";
}
That is spitting out 122461,4876192 how do I use "query" for separation?
I want to end up doing this
<td>122461</td><td>4876192</td>
EDIT: the picture you showed is showing an array of arrays. The reason you are getting comma separated values is because the variable query is actually an array, so when you join it with a string, JS is just listing the values of the subarray in CSV format.
Personally, I think you don't even have to use jQuery for this task, sometimes it's a lot easier to use a couple of nested for loops. You have to loop through the main array, and then each of the subarrays and join them inside of <td> tasks. After that, you can use jQuery for anything you want to do with the elements.
var strData = "";
if (allData.Data) {
for (var i = 0; i < allData.Data.length; i++) {
if (allData.Data[i]) {
for (var j = 0; j < allData.Data[i].length; j++) {
strData += '<td>' + allData.Data[i][j] + '</td>';
}
}
}
}
However, if you really want to use the jQuery each function, you can do
var strData = "";
if (allData.Data) {
$.each(allData.Data, function(i, query) {
// Note this will skip everything that equals to false in JavaScript
// not just null, for example, "", false, 0, etc...
if (!query) return;
$.each(query, function(j, value) {
// See note above
if (!value) return;
strData += '<td>' + value + '</td>';
});
});
}
There's a variety of shortcuts you can take using built-in array functions, such as join as #zan suggested in his answer.
EDIT 2: Added null checks
EDIT 3: Added null checks to jQuery
What you need is
var strData = ''
$.each(alldata.Data, function (index, query) {
strData += "<td>" + query.join('</td><td>') + "</td>";
})
console.log(strData)
Why That is spitting out 122461,4876192 how do I use "query" for separation?
Because you are concatenating Array with String
"myString" + [1,2,3,4] + "otherString"
will give you this output
"myString1,2,3,4otherString"
Try this:
If query is string:
$.each(alldata.Data, function (index, query) {
strData +='<td>'+query.split(',').join('</td><td>')+'</td>';
}
if Query is array then use this:
$.each(alldata.Data, function (index, query) {
strData +='<td>'+query.join('</td><td>')+'</td>';
}
This will also works when you have more the 2 elements in array
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);
});
});
});
I'm using this code to import a CSV into a var using ajax, then, split the informatión delimited by the "\n" and then populate a Select Box I have in a form.
The CSV is pretty much flat, just 1 column with several rows. Added an alert to monitor the progress.. it all goes fine except when it comes to populate the combobox, instead of populating the String Content, it populates the number of row, for some reason the array is not recording string but row number.
<script>
$.ajax({
url: 'URL CSV',
success: function(data) {
alert(data);
var splitData=data.split("\n");
for(pn in splitData){
alert(splitData);
$('#Entry_ID').append("<option value=\""+pn+"\">"+pn+"</option>");
}
}
});
</script>
(the form combobox code)
<select name="Entry.ID" id="Entry_ID" aria-required="true"></option>
</select>
Your error is in the "for..in" loop. A code like this:
var arr = ["q", "w", "e"];
for (var i in arr) {
console.log(i)
}
will output:
0
1
2
The for..in loop takes the key of each item in the object and it is assigned to the var. In an array the key is its position.
The method split of String returns an array with all the items. To loop through the splitData array you can:
for (var i = 0; i < splitData.length; i++) {
alert(splitData[i]);
$('#Entry_ID').append("<option value=\"" + splitData[i] + "\">" +
splitData[i] + "</option>");
}
or
splitData.forEach(function (item) {
alert(item);
$('#Entry_ID').append("<option value=\"" + item + "\">" + item + "</option>");
});