Reload JSON data from javascript - javascript

I am trying to reload data every 5 seconds using jQuery. The URL for the JSON data can be found at http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json
This is the code I am trying:
$.getJSON("http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json", function (json) {
$.each(json.data.games.game, function (i, value) {
$('#LMP').append('<div id="equipo"><div class="p1"><img src="img/lmp/' + value.away_name_abbrev + '.png' + '" alt=""></div><div class="p2"><div class="p2-1"> </div><div class="p2-2">' + value.status.inning + ' ' + value.status.top_inning + '</div><div class="clear"></div></div><div class="p3"><img src="img/lmp/' + value.home_name_abbrev + '.png' + '" alt=""></div><div class="clear"></div></div>');
});
});

One way to do it might look like this:
function getJson () {
$.getJSON("http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json", function (json) {
$.each(json.data.games.game, function (i, value) {
$('#LMP').append('<div id="equipo"><div class="p1"><img src="img/lmp/' + value.away_name_abbrev + '.png' + '" alt=""></div><div class="p2"><div class="p2-1"> </div><div class="p2-2">' + value.status.inning + ' ' + value.status.top_inning + '</div><div class="clear"></div></div><div class="p3"><img src="img/lmp/' + value.home_name_abbrev + '.png' + '" alt=""></div><div class="clear"></div></div>');
});
});
}
var i = setInteval(getJson, 5000);

Related

How can i retrieve multiple data from remote php in nativescript javascript?

I'm trying to retrieve multiple data from my remote php file and display them dynamically, i usually do this with jquery when i'm coding cordova. i'm using nativescript now.
This is the jquery code i use before
$.getJSON(serviceURL + 'getroutes.php?station='+station, function(data) {
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li>'+
'<img src="js/citybus.png" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + '</p>' +
'<p class="line2">' + difference + ' Out' + '</p>' +
'<p class="line3" style="color:'+ color +';margin-left:60px">' + SeatsLeft + ' seats left </p>' +
'<button style="display:'+ display +'" class="bubble" data-difference="' + hoursMin + '" data-route="' + employee.firstName + '" data-busnum="' + employee.lastName + '" onclick="bookSeat(this);">' + '<center><img src="js/seat.jpg" style="height:15px;width:15px;"/></center>' + '</button>'
+ '<button data-id="' + employee.id + '" data-diff="' + hoursMin + '" data-name="' + employee.firstName + '" class="bubble" style="margin-right:30px" onclick="setReminder(this);">' + '<center><img src="js/bell.png" style="height:15px;width:15px;"/></center>' + '</button></li>');
if(index && index % 4 === 0) {
$('#employeeList').append('<center><div class="adSpace2" style="margin-top:2.5px;margin-bottom:2.5px;">'+'</div></center>');
}
});
setTimeout(function(){
scroll.refresh();
});
});
Please how do i do this with nativescript?
You'll want to use the Fetch API.
const Observable = require('tns-core-modules/data/observable').Observable
const model = new Observable()
function loaded(args) {
args.object.bindingContext = model
fetch(serviceURL + 'getroutes.php?station='+station).then(res => model.set('employees', res.items))
}
exports.loaded = loaded
And then in your View XML:
<Page xmlns="http://www.nativescript.org/tns.xsd" xmlns:lv="nativescript-ui-listview" aloaded="loaded">
<StackLayout>
<ListView items="{{employees}}">
<Label class="line1" text="{{firstName}}" />
</ListView>
</StackLayout>
</Page>

how to start each function from index 1 to post json objects in different div in html

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))
}

Append an HTML block after another appended block

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?

Display php data json_encoded with ajax

I convert my php code to json with json_encoded function.
After I write ajax code to display my data in ajax but when running don't display my data.
My json code:
[
{"Name":"fasher","Description":"2500 kg","Namyandegi":"20,500,000","Bazar":"22,410,000"}
,
{"Name":"shob","Description":"1000 kg","Namyandegi":"10,400,000","Bazar":"12,220,000"}
]
and ajax file:
<script type='text/javascript'>
$(document).ready(function(){
$.getJSON('saipa.php', function(data) {
$.each(data, function(key, val) {
$('ul').append('<li id="shoker">' + val.Name + ' ' + val.Description + ' ' + val.Namyandegi + ' ' + val.Bazar + '</li>');
});
});
});
</script>
<body>
<ul><li id="shoker"></li></ul>
</body>
Use the index overload $.each()
$.each(data, function(index) {
$('ul').append('<li id="shoker">' + data[index].Name + ' ' +
data[index].Description + ' ' +
data[index].Namyandegi + ' ' +
data[index].Bazar + '</li>'
);
});

How to return a value from javascript function [duplicate]

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)

Categories