I am a final year student and am creating a food log web application for my major project. I have created a search function that allows me to search and display external API results, but now I wish to display them in a table, can anyone help please?
I would prefer if it would be a table that can be filtered, eg, the columns ordered ascending/descending?
Thanks
function get foodItem(userInput) {
var storedSearchItem;
$('.resultContainer').html('');
$.ajax({
type: 'GET',
async: false,
url: 'https://api.nutritionix.com/v1_1/search/'+userInput+'?'+
'fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=325062a4&appKey=bf1a30b2066602dc6f33db888cd53bd3',
success: function(d) {
storedSearchItem = d.hits;
}
});
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}//ends get result function
function searchValue() {
var formVal = document.getElementById('itemSearch').value; //value from search bar
getFoodItem(formVal);
}
$('#searchForm').submit(function(e) {
e.preventDefault();
});`
You need to append your table in the success function
your code will look like something like this
success: function(d) {
storedSearchItem = d.hits;
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}
Related
i have json data which i want to display in html div using for loop. my control in entering in loop but not appending and displaying data in html div.
json data;
[{"id":"15","FirstName":"ranjan","MiddleName":"","LastName":"","Gender":"","Location":"r","Email":"ranjan.gupta.1994#gmail.com","Mobile":""},{"BookTitle":"","BookGenre":"","BookWriter":"","BookDescription":""}]
code;
$.getJSON(url, function(data) {
console.log(data);
if (data) {
alert("hey got the data" + JSON.stringify(data));
for (var i = 0; i < data.length; i++) {
alert("entered");
alert("hey got the data" + JSON.stringify(data[1]));
var $appendData =
$('<div id="' + data[i].id + '">' + '<p>'
+ 'FirstName:' + data[i].data.FirstName + '<br/>'
+ 'MiddleName:' + data[i].data.MiddleName + '<br/>'
+ 'LastName:' + data[i].data.LastName + '<br/>'
+ 'Gender:' + data[i].data.Gender + '<br/>'
+ 'Location:' + data[i].data.Location + '<br/>'
+ 'Email:' + data[i].data.Email + '<br/>'
+ 'Mobile:' + data[i].data.Mobile + '<br/>'
+ '</p>' + '</div>').appendTo('#postjson');
}
} else {
return;
}
// this is my div
</script>
<div class="grid" id="postjson"></div>
</div>
</div>
You got typo on your loop, just replace all your data[i].data.property with data[i].property
Javascript
$.getJSON(url,function(data) {
console.log(data);
if(data){
alert("hey got the data"+JSON.stringify(data));
for(var i=0; i<data.length; i++) {
alert("entered");
alert("hey got the data"+JSON.stringify(data[1]));
$('<div id="'+data[i].id+'">'
+'<p>'
+'FirstName:'+data[i].FirstName+'<br/>'
+'MiddleName:'+data[i].MiddleName+'<br/>'
+'LastName:'+data[i].LastName+'<br/>'
+'Gender:'+data[i].Gender+'<br/>'
+'Location:'+data[i].Location+'<br/>'
+'Email:'+data[i].Email+'<br/>'
+'Mobile:'+data[i].Mobile+'<br/>'
+'</p>'
+'</div>').appendTo('#postjson');
}
}
else {
return;
}
JsFiddle
I have this json data
somehow i displayed this part of data in html
and want to display this part of data
into div in html but i am unable to display it using for loop and don't to how to start each function from index 1 as index 0 in personal details data.
here is my code
var url = "http://localhost/ReadExchange/api.php";
$.getJSON(url, function(data) {
if (data) {
alert("hey got the data" + JSON.stringify(data));
var arr = data.length;
//$.each(data, function(i,element) {
var element = data[0];
$("#postjson").append(
'<div id="' + element.id + '">' + '<p>' + 'FirstName:' + element.FirstName + '<br/>'
+ 'MiddleName:' + element.MiddleName + '<br/>' + 'LastName:' + element.LastName + '<br/>' + 'Gender:' + element.Gender + '<br/>' + 'Location:' + element.Location + '<br/>' + 'Email:' + element.Email + '<br/>' + 'Mobile:' + element.Mobile + '<br/>' + '</p>' + '</div>'
);
for (var i = 1; i < arr; i++) {
$("#postjson").append(
'<div id="">' + '<p>' + 'BookTitle:' + data[i].data.BookTitle + '<br/>' + 'BookGenre:' + data[i].data.BookGenre + '<br/>' + 'BookWriter:' + data[i].data.BookWriter + '<br/>' + 'Gender:' + data[i].data.BookDescription + '<br/>'
+ '</p>' + '</div>'
);
}
} else {
return;
}
You can use Array.prototype.splice()
data.splice(0, 1);
then iterate data array at for loop, with i set to 0
var data = [{abc:123}, {def:456}];
data.splice(0, 1);
for (var i = 0; i < data.length; i++) {
alert(JSON.stringify(data))
}
I have an ajax script that retrieves more X results from the database. The number of results depend on the offset hidden field value. The script doubles it. After these X new data, it should append after it another block of an image, but I noticed that if I print in the console the selected element, it shows this:
[prevObject: m.fn.init[1], context: document, selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"]context: documentlength: 0prevObject: m.fn.init[1]selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"proto: Object[0]
[prevObject: m.fn.init[1], context: document, selector: "#revendas_conteudo .load_more .item_estoque:nth-child(6)"]context: documentlength: 0prevObject: m.fn.init[1]selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"proto: Object[0]
Which means it's trying to append to something that still doesn't exist. Below is the Ajax script:
function appendAd(offset, no) {
console.log($('#revendas_conteudo .load_more .item_estoque:nth-child(' + offset + ')'));
$('#revendas_conteudo .load_more .item_estoque:nth-child(' + offset + ')').after(
'<div style="float: left; margin-top: 8px; margin-bottom: 8px; width: 100%; text-align: center;" class="anuncio">' +
'<img src="/uploads/publicidades/publicidade_busca_' + no + '.jpg">' +
'</div>'
);
}
$('#revendas_conteudo .btn_carregar_mais').on('click', function (e) {
$.ajax({
url: '/auto/carros/load_more',
data: {
'offset': $('#offset').val(),
'limit': $('#limit').val(),
'no': $('#no').val()
},
success: function (data) {
obj = JSON.parse(data);
i = 0;
max = obj.total === obj.offset;
var newOffset;
no = parseInt($('#no').val()) + 1;
$('#limit').val(obj.limit);
$('#offset').val(obj.offset);
$('#no').val(obj.no);
$.each(obj.res, function (k, v) {
newOffset = parseInt($('#offset').val()) + 1;
$('#revendas_conteudo .load_more').append(
'<div class="item_estoque">' +
'<div class="avatar">' +
'<img src="/uploads/carros/destaque/' + obj.res[i].imagem_destaque + '"/>' +
'</div>' +
'<div class="texto_anuncio">' +
'<h4>' + obj.res[i].modelo.substring(0, 19) + '</h4>' +
'<div class="detalhes">' +
'<span>' + obj.res[i].marca + ' | ' + obj.res[i].combustivel + ' | ' + obj.res[i].cor + '</span>' +
'<span>' + obj.res[i].ano + '</span>' +
'<span>' + obj.res[i].kilometragem + ' km</span>' +
'</div>' +
'<span class="anunciante">' + obj.res[i].nome_anunciante + '</span>' +
'</div>' +
'<div class="texto_anuncio_right">' +
'<span class="preco"> R$ ' + obj.res[i].preco + '</span>' +
'Veja Mais' +
'</div>' +
'</div>'
);
i++;
$('#offset').val(newOffset);
$('#no').val(no);
if (newOffset == obj.total) {
$('#revendas_conteudo .btn_carregar_mais').css({backgroundColor: '#999'}).html('Sem mais resultados').attr('disabled', true);
}
});
},
complete: function() {
appendAd($('#offset').val(), no);
}
});
});
How can I do it? To append a block after another HTML block has been appended?
How I can load dynamicly (like $.ajax or getjson) in selectize options list?
Searched thru the forum, looks like nobody did it this way for some reason (?)
Thanks.
The load(fn) method is probably what you are looking for.
Loads options by invoking the the provided function. The function
should accept one argument (callback) and invoke the callback with the
results once they are available.
Here is the first Remote Source example:
$('#select-repo').selectize({
valueField: 'url',
labelField: 'name',
searchField: 'name',
create: false,
render: {
option: function(item, escape) {
return '<div>' +
'<span class="title">' +
'<span class="name"><i class="icon ' + (item.fork ? 'fork' : 'source') + '"></i>' + escape(item.name) + '</span>' +
'<span class="by">' + escape(item.username) + '</span>' +
'</span>' +
'<span class="description">' + escape(item.description) + '</span>' +
'<ul class="meta">' +
(item.language ? '<li class="language">' + escape(item.language) + '</li>' : '') +
'<li class="watchers"><span>' + escape(item.watchers) + '</span> watchers</li>' +
'<li class="forks"><span>' + escape(item.forks) + '</span> forks</li>' +
'</ul>' +
'</div>';
}
},
score: function(search) {
var score = this.getScoreFunction(search);
return function(item) {
return score(item) * (1 + Math.min(item.watchers / 100, 1));
};
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'https://api.github.com/legacy/repos/search/' + encodeURIComponent(query),
type: 'GET',
error: function() {
callback();
},
success: function(res) {
callback(res.repositories.slice(0, 10));
}
});
}
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the following function from where i want to return the htm value however i am getting an undefined. I get a return value as i have checked that already.
function loadData(uid) {
$.ajax({
type: "POST",
url: '<%= page.resolveURL("~")%>Haggler.asmx/getLovedProductsSellerStoreByFbId',
//url: '<%= Page.ResolveUrl("~")%>Haggler.asmx/GetFacebookFriends',
data: '{FacebookId:' + uid + ',pageIndex:' + JSON.stringify(pageIndex) + '}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: true,
// Page parameter to make sure we load new data
success: function (data) {
var myObject = eval('(' + data.d + ')');
//alert('getProductDescription' + JSON.stringify(myObject));
var html = '';
pageIndex++;
var htmlCategoryList = '';
var i = 0, length = myObject.length;
var _productLink = '';
var _productFullLink = '';
if (length > 0) {
pageCount = myObject[0].PageCount;
if (length > 0) {
for (; i < length; i++) {
if (myObject[i].ShippingQuantity > 0) {
_productLink = myObject[i].SellReqID + '/product/' + myObject[i].CurrentNodeName;
_productFullLink = "http://www.xarato.com/" + myObject[i].SellReqID + "/product/" + myObject[i].CurrentNodeName;
if (myObject[i].Discount == 0) {
/**
if (parts[parts.length-1] == 'loves') {
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><a href="/' + _productLink + '"><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].
html += '<li class="polaroid"><div style="position:relative;"><img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '"_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '"><div class="options"><span class="favs" id="span' + myObject[i].SellReqID + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].SellReqID + ')">like it!</span></div></div><div class="prod"><span>' + myObject[i].RequestTitle + '</span></div><div class="prodprice1"><span style="font-weight:700;">Rs. ' + Math.round(parseFloat(myObject[i].MRPrice) + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{ **/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
else {
/**if (parts[parts.length-1] == 'loves') {
var _finalPrice = parseFloat(myObject[i].MRPrice) - (parseFloat(myObject[i].Discount) * parseFloat(myObject[i].MRPrice))/100
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].Preview + '_thumb.jpg" width="200" height="' + myObject[i].Height + '"><div class="options"><span class="favs" id="span' + myObject[i].NodeId + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].NodeId + ')">like it!</span></div><div class="kjss"><span>' + myObject[i].Discount + '% Off</span></div></div><div class="prod"><span>' + myObject[i].NodeName + '</span></div><div class="prodprice1"><span style="color:#777777; text-decoration:line-through">Rs. ' + myObject[i].MRPrice + '</span> <span style="font-weight:700;">Rs. ' + Math.round(_finalPrice + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{**/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
}
}
if (clearHtml) {
// $('.bxslider').html('');
//htm = '<li>"' + html + '"</li>';
}
// var htmli = '<li>"' + html + '"</li>';
// $('.bxslider').append(htmli);
htm = '<li>' + html + '</li>';
alert(htm);
return htm;
clearHtml = false;
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#main'), // Optional, used for some extra CSS styling
offset: 17, // Optional, the distance between grid items
itemWidth: 225 // Optional, the width of a grid item
};
}
else {
return;
}
}
else {
return;
}
},
failure: function (data) {
alert('failture');
},
error: function (data) {
alert(data.responseText);
}
});
}
This is how i am taking the data but i get an undefined value.
HtmlM += loadData(myObject.data[i].uid);
Please help me out.
Change your loadData to
function loadData(uid, delegate) {
///In ajax instead of return use
delegate(htm);
}
then call like that
loadData(myObject.data[i].uid, function(html){ HtmlM += html ;});
Ajax is asynchronous so you cant just return (yes you can do it synchronous but its not right way)