Looping through AJAX result and post to HTML, - mysql

I have the following AJAX code for processing a returned results from the database,
$.ajax({
type: 'POST',
async: true,
url: "../../../avocado/private/functions/measures.php",
data: {name:selectedValue},
success: function(data, status){
var selectedData = JSON.parse(data);
console.log(selectedData);
document.getElementById("measures").innerHTML = "<div id=\"measures\">"
+ "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[0][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[0][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[0][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[0][9]+"</td></tr>"
+ "</table>"
+ "</div>";
},
error: function(xhr, status, err) {
alert(status + ": " + err);
}
});
The data returned is a 2D array, like this below,
Array[5]
0: Array[14]
1: Array[14]
2: Array[14]
3: Array[14]
4: Array[14]
so what I want to do is to loop each array and display the inner information on the HTML page but I have no idea how I should go about doing it.. this code only returns the values stored on index[0].
Can I please get some help?
==============================================================================
UPDATED
So I tried to use Jquery.append() like the following below..
jQuery.each( selectedData, function( i, val ) {
$("measures").append(
"<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[i][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[i][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[i][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[i][9]+"</td></tr>"
+ "</table>"
);
});
/*
document.getElementById("measures").innerHTML = "<div id=\"measures\">"
+ "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[0][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[0][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[0][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[0][9]+"</td></tr>"
+ "</table>"
+ "</div>";
*/
now..its not appending any values to the div #measures at all...

I have not tried the code. But I hope this will help you.
document.getElementById("measures").innerHTML = "<div id=\"measures\">";
$.each( selectedData, function( index, value ){
$.each( index, function( index2, value2 ){
$('#measures').append(value2);
});
});

Related

Pass parameter to href of a table cell in ajax

I'm new to use ASP.net for web app programming. I'm using the following ajax function aiming to send a parameter to the controller with the name of yyy. However, no matter how I manipulate the variable {id} in this case, the controller either get the string {id} or null. The variable of {id} is actually storing an integer value, for example, 3. I want to pass the integer 3 to the controller. Please help! Thanks!
$.ajax({
type: "GET",
url: "http://localhost:8086/xxx",
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var testData = '';
$.each(data, function (key, value) {
testData += '<tr>';
var id = value.testDataID.toString();
testData += '<td style="cursor:pointer">' + '<a href="http://localhost:8087/xxx/yyy?param="+{id}>' + value.serialNumber + '</a>' + '</td>';
testData += '<td>' + value.testDataID + '</td>';
testData += '<td>' + value.sN + '</td>';
testData += '</tr>';
});
$('#testDataTable').append(testData);
}
});

JQuery Cannot use 'in' operator to search for 'length' in using Ajax reponse

[{"ContainerNo":"FCIU3554053","Size":20,"SealNo":"172003","Weight":25209.00},{"ContainerNo":"TEMU5422909","Size":20,"SealNo":"164169","Weight":25400.00}]
$.ajax({
url: "/Popu/GetContainers",
dataType: "json",
complete: function (response) {
var parsedJson = JSON.parse(response.responseText);
var thead = '', tbody = '';
//for (var key in parsedJson[0]) {
// thead += '<th>' + key + '</th>';
//}
thead += '<th>ContainerNo</th><th>Size</th><th>SealNo</th><th>Weight</th>';
$.each(parsedJson, function (i, d) {
tbody += '<tr><td>' + d.ContainerNo + '</td><td>' + d.Size + '</td><td>' + d.SealNo + '</td><td>' + d.Weight + '</td></tr>';
});
callback($('<table style="padding-left:20px;">' + thead + tbody + '</table>')).show();
}
I am getting the error Uncaught TypeError: Cannot use 'in' operator to search for 'length'. I am very confused. I get the same error when doing - parsedJson.Count.
First, you have an Array of objects:
var foo = '[{"ContainerNo":"FCIU3554053","Size":20,"SealNo":"172003","Weight":25209.00},{"ContainerNo":"TEMU5422909","Size":20,"SealNo":"164169","Weight":25400.00}]';
Note: string (enclosed in single quotes) to justify using JSON.parse, otherwise, if the response were already an Array then you don't need to parse.
var parsed = JSON.parse(foo)
// iterate over your array
for(i = 0; i < parsed.length; i ++){
console.log(`Container No: ${parsed[i].ContainerNo}, Seal No: ${parsed[i].SealNo} `);
}
Output:
Container No: FCIU3554053, Seal No: 172003
Container No: TEMU5422909, Seal No: 164169
If you want to use Array.forEach:
parsed.forEach( i => console.log(`Container No: ${i.ContainerNo}, Seal No: ${i.SealNo} `));
Output:
Container No: FCIU3554053, Seal No: 172003
Container No: TEMU5422909, Seal No: 164169

I'm having trouble parsing response from $.ajax

I'm trying to modify some old code of mine to include comments for photos. The photos are acquired using $.ajax and the response is in html.
My modification is to get the comments as a json object and then parse the previously attained html inserting the comments where appropriate. Here is the [latest incarnation] of my code (I've tried many different alternatives)
$.ajax({
type:"POST",
url:"<?php echo $_SERVER['PHP_SELF']; ?>",
data:"ajax_loadbigthumbs=true&section=<?php echo $_GET['section']; ?>",
dataType : "html",
success: function(html){
jhtml = $(html);
$.getJSON( "/commentsjson.php?getcomments=true&section=<?php echo $_GET['section']; ?>", function( data ) {
$.each(data,function(i,item){
//alert(item.comment); <--- this works so I know the data is coming back correctly
console.log(jhtml.find('#comments_' + item.photoid).attr("id")); // this shows 'undefined'
jhtml.find('#comments_' + item.photoid).css("display","block").html("<p>" + item.name + " said " + item.comment + "</p>");
});
$("#largethumbscontainer").append(jhtml);
});
}
});
But this isn't working. The console.log line (as a test) returns 'undefined' and the following line (jhtml.find) has not found anything to modify.
var $comment = $('#comments_' + item.photoid, jhtml);
if ($comment.length)
$comment.css("display","block").html("<p>" + item.name + " said " + item.comment + "</p>");
I fixed it, buy appending the html to an already existing element, and then appending the comments to that element....
$.ajax({
type:"POST",
url:"<?php
echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");
?>",
data:"ajax_loadbigthumbs=true&section=<?php echo $_GET['section']; ?>",
dataType : "html",
success: function(html){
jhtml = $(html);
$("#largethumbscontainer").append(jhtml);
largethumbs = $("#largethumbscontainer");
$.getJSON( "/commentsjson.php?getcomments=true&section=<?php
echo $_GET['section'];
?>", function( data ) {
$.each(data,function(i,item){
largethumbs
.find('#comments_' + item.photoid)
.css('display','block')
.append('<p>' +
item.name +
' said: <span style="font-style:italic;">' +
item.comment +
'</span></p>');
});
});
}
});

Converting html to Json object

I'm currently working on a project where I need to convert some older code into a json object. We're taking the result set from a sql query and returning the categories it gives back as json. I'm not that well versed in javascript let alone json so I'm not sure what's the simplest way to go about this. Here is the function I need to change into JSON:
function createOutputCategories(){
try
{
output =
"<html>" +
"<head>" +
"<title>" +
"You can find it!" +
"</title>" +
"</head>" +
"<body bgcolor='#CED3F3'>" +
"<a href='" + url + "file.xsjs?parent=1'>" +
"</a>" +
"<br><br>";
if(parent === "1"){
output = output + "<h3><font color='#AAAAAA'>Home</font>";
}else{
output = output +"<a href='javascript:history.back()'>" +
"<h3>Back";
}
output = output +
"</h3>" +
"</a>" +
"<h1>" +
"Categories:" +
"</h1>";
while(rs.next()){
if(rs.getString(3) === 0 || rs.getString(3) === null || rs.getString(3) === undefined || rs.getString(3) === "0" ){
output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(2) + "</a>";
}else{
output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(3) + "</a>";
}
}
}catch(Exception){
$.response.contentType = "text/plain";
$.response.setBody( "Failed to retreive data" );
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
Here is what I have so far but I am not returning a valid JSON object:
function createOutputCategories(){
try{
output =
"category: {name = \"" + parent + "\"; description = \"\"}";
output = output +
"subcategories: [ ";
while(rs.next()){
output = output +
"{ catid = \"" + rs.getString(1) + "\"; catname = \"" + rs.getString(2) + "\"; altname = \"" + rs.getString(3) + "\"; description = \"" + rs.getString(4) + "\"}";
}
output = output +
"];";
}
catch(Exception){
$.response.contentType = "text/plain";
$.response.setBody( "Failed to retreive data" );
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
If I need to provide anything else please let me know! Thanks!
Do you want to output a javascript object to a string?
Construct the object:
var category=new Object();
category.name="Name";
category.description="My lovely description";
category.subcategories=[];
var subCat=new Object();
subCat.catid=1;
subCat.catname="My subcat";
category.subcategories.push(subCat);
Alternatively, you could construct the object using literals:
var category={
name:"Name",
description:"My lovely description",
subcategories:[
{catid:1,catname:"My subcat"}
]
};
Then return the object as string.
return JSON.stringify(category);
A reference to Javascript objects if you need more help:
http://www.w3schools.com/js/js_objects.asp

Loop stopping when undefined

UPDATE 6:
Based on the console.log, I have noticed that some of the objects have:
thumbnail: Array[2]
Others have:
thumbnail: Object
and others don't have it at all.
So it seems that what #Felix Kling could be true.
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20%22http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Frss.xml%22&format=json&callback=cbfunc
if you can't access the link, try:
http://pastebin.com/T4GPQvtk
UPDATE 5:
I am still getting url as undefined with:
for (var i = 0; i < news.length; i++) {
news[i].thumbnail = ( $.isArray( news[i].thumbnail ) ) ? news[i].thumbnail : [news[i].thumbnail];
buildHTML.push( "<a href='" + news[i].thumbnail[0].url + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
}
UPDATE 4:
The following:
buildHTML.push( "<a href='" + news[i].thumbnail[0] ? news[i].thumbnail[0].url : $.isArray( news[i].thumbnail ) + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
gives me:
Uncaught TypeError: Cannot read property 'url' of undefined
UPDATE 3:
The following does not seem to work either:
buildHTML.push( "<a href='" + news[i].thumbnail[0] ? news[i].thumbnail[0].url : news[i].thumbnail.url + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
The error I get is:
Uncaught TypeError: Cannot read property 'url' of undefined
UPDATE 2:
The following does not seem to work:
buildHTML.push( "<a href='" + news[i].thumbnail=$.isArray(news[i].thumbnail)?news[i].thumbnail:[news[i].thumbnail] + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
The error I get is:
Uncaught ReferenceError: Invalid left-hand side in assignment
$.ajax.successyql_news_widget.js:25
bjquery-1.4.2.min.js:124
c.extend.ajax.Ajquery-1.4.2.min.js:125
(anonymous function)yql:1
UPDATE 1:
The problem happens, when I add the image to push as follows:
buildHTML.push( "<img src='" + news[i].thumbnail[0].url + "' /><a href='" + news[i].link + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
ORIGINAL QUESTION:
From the following url:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20%22http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Frss.xml%22&format=json&callback=cbfunc
I am trying to capture the data via a look like this:
function get_news() {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20%22http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Frss.xml%22&format=json&callback=cbfunc&rand=" + Math.random(),
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc',
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
var buildHTML = [];
var news = data.query.results.rss.channel.item;
for (var i = 0; i < news.length; i++) {
buildHTML.push( "<a href='" + news[i].link + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
}
$('.portlet-content').empty().append(buildHTML.join("<br /><br />"))
}
});
}
This works fine as long as the thumbnail section looks like this:
"thumbnail": [
{
"height": "49",
"url": "http://news.bbcimg.co.uk/media/images/48915000/jpg/_48915868_48915872.jpg",
"width": "66"
}
{
"height": "81",
"url": "http://news.bbcimg.co.uk/media/images/52468000/jpg/_52468689_48915872.jpg",
"width": "144"
}
]
However, when the thumbnail section looks like this:
"thumbnail": {
"height": "81",
"url": "http://news.bbcimg.co.uk/media/images/53705000/jpg/_53705922_012314461-1.jpg",
"width": "144"
}
I get an error "undefined", the loop stops and I get nothing on the screen.
How do I ignore those, and continue the script without it stopping on the error?
You may create an array if the json matches the 2nd example(isn't an array yet):
news[i].thumbnail=($.isArray(news[i].thumbnail))
? news[i].thumbnail
: [news[i].thumbnail];
Based on your comments, you seem to want this:
for (var i = 0; i < news.length; i++) {
var item = news[i];
if($.isArray(item.thumbnail)) {
var size = +item.thumbnail[0].width * +item.thumbnail[0].height,
selected = 0;
for(var j = 1, jl = item.thumbnail.length; j < jl; j++) {
var t_size = +item.thumbnail[j].width * +item.thumbnail[j].height;
if(t_size < size) {
size = t_size;
selected = j;
}
}
buildHMTL.push("<img src='" + news[i].thumbnail[selected].url + "' />");
}
buildHTML.push( "<a href='" + item.link + "' target='_blank'>" + item.title + "</a><br />" + item.pubDate );
}
Add [] brackets to cast "thumbnail" from object to array.
"thumbnail": [ {
"height": "81",
"url": "http://news.bbcimg.co.uk/media/images/53705000/jpg/_53705922_012314461-1.jpg",
"width": "144"
}]
will work
You can use a Try catch or a simple IF before the code to check to see if the code is in the format you want before attempting to manipulate it. The issue seems to be that if your thumbnails 'array' is only one object its not sent as an array. A simple if check could stop this issue your having.
you can use a conditional operator which would go something like this:
buildHTML.push( "<img src='" + news[i].thumbnail[0] ? news[i].thumbnail[0].url : news[i].thumbnail.url + "' /><a href='" + news[i].link + "' target='_blank'>" + news[i].title + "</a><br />" + news[i].pubDate );
UPDATE
this conditional expression will find the URL or it will just return "". I didn't see that some items have no URL which is why my first suggestion didn't work. Use this expression for getting your url
news[i].thumbnail ? news[i].thumbnail[0] ? news[i].thumbnail[0].url : news[i].thumbnail.url : ''