So I am looking for a little bit of guidance, tips and knowledge transfer. Currently I am practicing fetching JSON data, but I am having some issues.
My current problem I a running into is that my 3 variable (brand, desc and price) give me this error: Uncaught TypeError: Cannot read property 'Brand' of undefined
Can someone help me with this, also tips on better coding would be nice.
var url = 'https://raw.githack.com/gromstone/jsonFiles/master/products.json';
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
success: function(data){
console.log(data);
$.each(data, function(i, products){
var content = "<div class=\"item grid_4\">";
$.each(products, function(i, mainProd){
var brand = mainProd.ProductInfo.Brand,
desc = mainProd.ProductInfo.p_product_description,
price = mainProd.ProductInfo.p_product_price;
//content += '<img class="scale-with-grid" src="' + src + '"/>';
content += '<p>' + brand + desc + '</p>';
content += '<p>' + price + '</p>';
content += '<a>View More</a>';
});
content += "</div><!-- product -->";
$('.load').append(parent);
})
},
error: function(){
alert('Data did not load, or no connection')
}
});
You can see working code here:
http://jsfiddle.net/gromstone/j1etxuw0/1/
Also if anyone can provide additional help, I want to make a hover effect for each one of the 'div.items' where some additional data is shown on a separate div (ex 'div.placeHolder')
Thanks!
The problem seems to be that you're looping over all properties of the object that your receive in the outer loop
$.each(data, function(i, products){
and in the inner loops you're expecting these properties to be arrays, and each array member to have a ProductInfo property:
$.each(products, function(i, mainProd){
var brand = mainProd.ProductInfo.Brand,
However, the top-level properties of your JSON document are:
[
"ProductsList",
"RecordsCount",
"nValue",
"Pages",
"Refinements",
"Breadcrumbs",
"CategoryName",
"sortProperty"
]
So your program will first loop over the internals of ProductsList (what I guess is what you expected it to do), but after that, it will loop over the contents of RecordsCount, which in the JSON you linked does not contain an array but the number 8. The inner loops in your program however expect it to be an array, and they will try to access a property ProductInfo of the (non-array) members, which will then fail with an error.
If you're only after iterating over the ProductsList of the JSON, removing the outer loop, and change the remaining (formerly inner) loop's each to:
$.each(data.ProductsList, function(i, mainProd){
Related
I'm only posting relevant code here. I'm trying to access an array in a json array. How do I access an array inside an array?
So this is the code serverside :
$scriptfull = array();
while($r = mysqli_fetch_assoc($resultstmt_scriptfull)) {
$scriptfull[] = $r;
}
$resulterr = array('message' => 'Success',
'fullscript'=>$scriptfull);
header('Content-Type: application/json');
echo json_encode($resulterr);
I know how to access JSON array in Javascript. The problem I do not know how to access a base object that is itself an array within a JSON array.
When I do :
success: function(output)
{
console.log(output.fullscript);
}
I see result in console
(1)[...]
0:{...}
scriptAA1: "a1"
scriptAA10: "a10"
scriptAA2: "a2"
scriptAA3: "a3"
But nothing prints in the HTML if I try
success: function(output)
{
$('.scriptview').html(output.fullscript);
}
I tried accessing it using below code but nothing prints:
success: function(output)
{
$('.scriptview').html(output.fullscript[1]);
}
What you are doing is trying to print a javascript array of objects at html which of course does not make sense and that why nothing is printed. You can either print the javascript array as a string (which probably is not what you want) like this:
$('.scriptview').html(JSON.stringify(output.fullscript));
I think you should explain better what exactly you are trying to print to html.
Edit:
As I understood you want something like what you are getting in your console. For something like this, the code below will do:
var outputString = '';
output.fullscript.forEach(function(object, index){
outputString += '<br> Object with index: ' + index + '<br>';
for (var prop in object){
outputString += 'Property ' + prop + ': ' + object[prop] + '<br>';
}
});
$('.scriptview').html(outputString);
Since you are trying to output the result as a string, you can use
success: function(output)
{
$('.scriptview').html(JSON.stringify(output.fullscript));
}
Update1
If you want the result formatted with whitespaces, the 3rd argument of the stringify method does that:
success: function(output)
{
$('.scriptview').html(JSON.stringify(output.fullscript, null, '\t'));
}
Update2
A more shorter, readable and efficient way is to just display using the jQuery text method instead of html:
success: function(output)
{
$('.scriptview').text(JSON.stringify(output.fullscript, null, '\t'));
}
This looks more tidy...
I am using jquery ajax to get some data from server and I get them back in this format:
however when I print this data in javascript it gets printed ascending by id instead of descending like the data I recieved.
when I print it here it is how it looks:
it self orders everything in ascending order by letter and number, why does it do this?
Here is my code:
$.ajax("{{route("backend.blog.categories.getparents")}}", {
method: 'GET',
dataType:'json',
success: function(result) {
console.log("result.categories: " + result.categories);
I use this data to populate a select box and I need it to be in the same order I recieve it in and not ordered by javascript automatically. How do I do this?
$.each( result.categories, function( key, value ) {
console.log("key: " + key);
if(key != exclude){
parentCategories += '<option value=' + key + '>' + value + '</option>';
}
});
code on the server side:
$parentCategories = array();
foreach ($categories as $category) {
$parentCategories += [$category->id => $category->title];
}
if($categories){
return response()->json([
'status' => 'success',
'categories' => $parentCategories,
JSON - the notation you're using - doesn't have an order. If you want to give it a specific order you will have to save that explicitly or use an array. Either way, although according to the spec the order is not guaranteed, modern browsers in general do keep the order. Numeric looking keys however form a weird exception that you found now.
let orderKept = {"a2": "a", "a1": "b"};
let orderNotKept = {"2": "a", "1": "b"};
console.log(orderKept, orderNotKept);
Example way how this would typically be done properly (guaranteed to work by the spec and not just browser implementations) is an array of objects where every object has its own id property.
Of course you could move away from JSON, but keep the same notation and build your own parser, however I would definitely not recommend that.
We're trying to run through a collection of objects with properties (key: value)'s and write it to the dom.
var productContent = {
item1: {
description: "description 1",
price: 1,
URL: "something1.com",
},
item2: {
description: "description 2",
price: 2,
URL: "something2.com",
},
We've tried a few different types of code, such as:
var productInfo;
var insertProduct = document.getElementById("productList");
for (var i in productContent) {
console.log(productContent[i]);
productInfo += productContent[i];
}
insertProduct.innerHTML = productInfo;
Nothing seems to be working. Any thoughts on how to approach this? We've been able to get properties shown in the console but not much else.
Your first codeblock has a syntax error. The productContent object is missing a closing curly brace: }.
You also have a comma after the last property instead of only between properties.
You should use the JS console in your browser's developer tools to debug this.
You have some errors in your script, you can start with following:
var htmlValue = '';
for (var productKey in productContent) {
var product = productContent[productKey];
htmlValue += 'description: ' + product.description + '<br>';
htmlValue += 'price: ' + product.price + '<br>';
htmlValue += 'url: ' + product.URL + '<br><br>';
}
insertProduct.innerHTML = htmlValue;
Errors:
1.
for (var i in productContent) {
This is just a strong suggestion, but you should change i to something meaningful for the context, such as key since you are iterating over object properties. Naming properly your variables will help you spot errors in your code.
2.
productInfo += productContent[i]
This is not the proper way to concatenate object values. First iteration and it will be "undefined[object Object]".
3.
insertProduct.innerHTML = productInfo;
What are you even trying to do here? You can't just put in element an object. You must put as code and formatted the way you want.
I've got a .each loop that is processing an object returned from a JSON feed a la Ajax (Type: jsonp; success function sends the "data" to the function/method that contains the .each loop).
What's got me scratching my head is that, if the feed returns more than one set of data, it parses it out just fine. But if the feed returns only ONE set of data, the loop is trying to break out the individual fields of that lone record, as if each field were a record itself.
Here are examples of the object that comes in from the Ajax routine:
Example 1: -- single item
{
"SmeDetail": {
"SipAddress": "jane.smith#whatever.com",
"SubjectExpert": "Smith,Jane",
"SubjectMatter": "Unix"
}
}
Example 2: -- multiple items
{
"SmeDetail": [
{
"SipAddress": "fred.flintstone#whatever.com",
"SubjectExpert": "Flintstone,Fred",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "barney.rubble#whatever.com",
"SubjectExpert": "Rubble,Barney",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "wilma.flintstone#whatever.com",
"SubjectExpert": "Flintsone,Wilma",
"SubjectMatter": "Bedrock"
}
]
}
Now, here's the .each routine:
$.each(json_data.SmeDetail, function (i,val){
var sip_address = val.SipAddress;
var SME_name = val.SubjectExpert;
var subject_matter = val.SubjectMatter;
var sip_link = "<a href='sip:" + sip_address +
"'><img src='http://server/prod/images/im.gif' hspace='2' border='0' title='Send an instant message to " +
SME_name + "' alt='Send an instant message to " +
SME_name + "'/></a>";
output7 = output7 + "<tr><td>" +
SME_name + " " + sip_link + "</td></tr>";
});
I put some alert statements in there so I could verify the data. And when this runs for a single record coming back from the feed, it loops three times and assigns "undefined" to all of the variables. So, because it's looping exactly three times, plus the fact that it's entering the loop at all, tells me it sees a "SmeDetail" record, but it's treating each individual field as a record.
Makes me wonder if the structure of that return of a single record is correct? Should there be brackets around that lone item?
var detail = json_data.SmeDetail;
if (!detail.length) detail = [detail];
$.each(detail,....
I need help understanding the best way to manipulate a JavaScript data structure (if you call it that?). I come from a Perl background and am trying to iterate through a JavaScript data structure to update a div (or table) on the fly. Currently I'm just making the data a variable (data) to get going. once I have that sorted then I will use jquery's ajax methods to get the data as a json object on the fly. It's my understanding that the data structure I'm currently generating is the same thing I would get if it were json?? if not then I guess thats another question..
I have searched many times for such a tutorial but they are all close but haven't found one that meets my needs...
I would like to in the future be able to re-order the array and repopulate the #data_table div so part of my question is: is this even the best way to represent the data? Then I want to update just one part of the array like a companies phone number or add a person then redraw the div from this updated array...
The end result to the user could look like:
Company: 99 Beans, Auckland, Ph: 360499
People:
Matt, 6471
Christiaan, 6472
Michelle, 6473
Judy, 6474
Company: ....
* Next company and so forth..
My code so far is like this (except I have 500+ entries in the data array and only 2 here):
I have taken some of this code from another question I found here and tried to make it work for my type of structure..
<script>
$(document).ready(function() {
var r = new Array();
var data= [
{
"id":"6477",
"c":"99 Beans",
"ci":"Auckland",
"p":"09 360499",
"co":[
{"id":"6471","c":" NZ", "n":"Matt" },
{"id":"6472","c":" NZ", "n":"Chrstiaan" },
{"id":"6473","c":" NZ", "n":"Michelle" },
{"id":"6474","c":" NZ", "n":"Judy " },
{"id":"6475","c":" NZ", "n":"Kate " },
{"id":"6476","c":" NZ", "n":"Unknown Person" }
]
},
{"id":"7145", "c":"A1 Ltd", "ci":"Te Puke ","p":"06 870090",
"co":[{"id":"7145","c":" NZ", "n":"Alan" }
]
},
];
// this alert used to work, when I had the data as an array of arrays so there must be a problem with how I'm referencing it or my data structure is wrong??
alert (data.length + " companies" );//+ data[455].co[0].n);
var j = -1;
for (var key=0, size=data.length; key<size; key++) {
// first div
r[++j] ='<div>';
r[++j] = data[key].id;
r[++j] = ' - ';
r[++j] = data[key].c;
r[++j] = ' - ';
r[++j] = data[key].p;
r[++j] = '<br />';
//inner div
var k = -1 ;
for (var key1=0, size1=data[key].d.length; key1<size1; key1++) {
r[++j] ='<div>';
r[++j] = data[key].d.[key1].n + ' - ' + data[key].d.[key1].c + ' - ';
r[++j] = '</div>';
}
r[++j] = '</div>';
}
$('#data_table').html(r.join(''));
});
</script>
<div id="data_table"></div>
JSON's representation in Javascript is a javascript object.
var json = {
my_property: 2,
another_property: 'string!'
}
You can then fetch properties with json.my_property or json['my_property'] (which is nice if you don't know what exactly you are fetching, you can do var something = 'something-the-user-selected'; json[something]).
So, with jQuery, you would so something like this:
var json = {}; // get this from the server using $.AJAX() or $.getJSON()
$("#my_table").append("<tr><td>" + json.my_property + "</tr></td");
Or, if you got an array of, say, tweets, you should iterate over them, maybe with underscore's each, jQuery's each or plain old for (var i = 0; i < json.tweets.length; i++).
The data structure you are referring to is JSON.
With jQuery you can easily iterate your data structure with .each() and treat the returned value as an object with the attributes defined.
Here is a sample making the an Ajax call that will build your JSON object and iterating:
$.ajax({
type: "POST",
url: "MySite/MyResource",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if(data.d.length > 0){
$(data.d).each(function(){$('#mytable').append("<tr><td>Company: " + this.c + "</td></tr>");});
}
},
error: function (xhr, status, error) {
// do something appropriate
}
});
If you are looking to iterate farther then you can continue to call .each()
If data is your JSON value, this will format your specified string. (You'll have to JSONify your string to create it as the actual JSON object)
data.each(function(){
$('#mydiv').append('Company: ' + this.c + ', ' + this.ci + ', Ph: ' + this.p + ' People: ');
this.co.each(function(){$('#mydiv').append(this.n + ', ' + this.id);});
});
For the "rendering an JSON object to HTML", you may want to have a look at jQuery.template() which allows to render pieces of HTML with a template syntax. I have never used it so I do not know how well it can perform with very big lists... (also note that it is still in beta)
UPDATE
Here is a working example (it might not be optimal or anything) but you should see the general idea ;)
http://jsfiddle.net/tsimbalar/A9uYP/
UPDATE 2 for sake of completeness and traceability
There was a syntax error in the original code which prevented the alert() from executing (and all following code).
See comment :
Your code is not working because of a syntax error in
data[key].d.[key1].n., which is invalid syntax. (it should be data[key].d[key1].n, I suppose. Use the Firebug extension ofr Firefox to detect this kind of issues that would otherwise go unnoticed.
After fixing this typo, it is easy to iterate over the contents of the object using jQuery.each() as mentioned by catalpa in another answer. You can then build HTML elements (i.e. $("<div/>")) and append them to existing items of the page with append() . (see the fiddle about that part)
handlebars js templating is far better than jquery template and can be used for rendering complex json objects in html