Below is the script:
$(document).ready(function () {
$.getJSON('table.json', function (data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
});
});
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000);
});
}
I want to update my data. The poll function is getting called after every 5 seconds which I checked through the alert. But data is not getting updated. Please tell me what I am doing wrong.
getJSON is a GET request so it will be cached. Set the proper no cache headers on the server.
Also look at your code, you are never processing the data
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000); //<--where is the processing you do nothing with the response???
});
}
$(document).ready(function() {
// make the initial JSON request
$.getJSON('table.json', init)
});
function poll() {
// make the subsequent JSON requests
$.getJSON('dummy.json', update);
}
function init(data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
}
function update(data) {
var rows = $("#mytable tr.tablecontent").toArray();
for (var i = 0, size = data.length; i < size; i++) {
if (rows[i])
rows[i].cells[3].firstChild.data = data[i].bid;
}
setTimeout(poll, 5000);
}
Here's the update function with more jQuery:
function update(data) {
$("#mytable tr.tablecontent > td:nth-child(4)")
.slice(0, data.length)
.text(function(i) {
return data[i].bid;
});
setTimeout(poll, 5000);
}
Related
function bookSearch() {
var search = document.getElementById('search').value
document.getElementById('results').innerHTML = ""
console.log(search)
var startIndex =
So I want to iterate the ajax call until it shows all the items and not just the 10. Can get 40 by using maxresults parameter. So the startIndex needs to change from 0 to 20 to 40 to 60 and so on after every iteration.
while (startIndex < 2000) {
$.ajax({
url: "https://www.googleapis.com/books/v1/volumes?q=" + search + "&startIndex=" + startIndex + "&maxResults=40",
dataType: "json",
success: function (data) {
console.log(data)
for (i = 0; i < data.items.length; i++) {
results.innerHTML += "<h2>" + data.items[i].volumeInfo.title + "</h2>"
results.innerHTML += "<h2>" + data.items[i].volumeInfo.authors + "</h2>"
results.innerHTML += "<h2>" + data.items[i].volumeInfo.publishedDate + "</h2>"
}
},
type: 'GET'
});
}
}
document.getElementById('button').addEventListener('click', bookSearch, false)
You can try this. Count total_items until it reach more than 40 and loop the function to print the results:
// start
var startIndex=0;
// button clicked
$("#button").click(function(){
$("#results").html('<img src="img/loader.gif" alt="" class="loader">');
var searchInput = $("#search").val();
getBooks(searchInput)
})
// onclick function run
function getBooks(search) {
RunApi(search, startIndex);
$("#results img").remove();
}
// run function to get results if available
function RunApi(search, start){
$.ajax({
url:"https://www.googleapis.com/books/v1/volumes?q=" + search + "&maxResults=40&startIndex="+start,
dataType: "json",
success: function(data) {
console.log(data)
totalItems = data.totalItems;
if(data.items){
for(i=0; i<data.items.length; i++){
if(data.items[i].volumeInfo){
var itemNubmer = startIndex+i;
results.innerHTML += "<h2>"+itemNubmer+": " + data.items[i].volumeInfo.title + "</h2>"
// results.innerHTML += "<h2>" + data.items[i].volumeInfo.authors + "</h2>"
// results.innerHTML += "<h2>" + data.items[i].volumeInfo.publishedDate + "</h2>"
}
}
}
// repeat the function
if(totalItems > 40){
startIndex+=40;
RunApi(search, startIndex);
}
},
type:'GET'
});
}
I think I am getting a logic problem using jQuery to fetch record from a service API with AJAX and using following piece of code.
There is no error but this code is repeating records in HTML table (Drafts) -
like twice.
success: function (data) {
if (data) {
console.log(data);
var textDraft = "";
for (var i = 0; i < data.TableDrafts.length; i++) {
textDraft += "<tr><td>" + data.TableDrafts[i].nMBM + "</td><td>" + data.TableDrafts[i].nMTM + "</td><td>" + data.TableDrafts[i].sType + "</td></tr>";
$("#Drafts").append(textDraft);
}
}
}
Here you go with a solution
success: function (data) {
if (data) {
console.log(data);
var textDraft = "";
for (var i = 0; i < data.TableDrafts.length; i++) {
$("#Drafts").append(`<tr>
<td>${data.TableDrafts[i].nMBM}</td>
<td>${data.TableDrafts[i].nMTM}</td>
<td>${data.TableDrafts[i].sType}</td>
</tr>`);
}
}
}
Mistake was, you are adding the new tr in the variable as well as appending the variable content.
Or else you can do
success: function (data) {
if (data) {
console.log(data);
var textDraft = "";
for (var i = 0; i < data.TableDrafts.length; i++) {
textDraft = "<tr><td>" + data.TableDrafts[i].nMBM + "</td><td>" + data.TableDrafts[i].nMTM + "</td><td>" + data.TableDrafts[i].sType + "</td></tr>";
$("#Drafts").append(textDraft);
}
}
}
Hope this will help you.
I'm having troubles with getting a variable from a getJSON() request. I have the following three functions:
function getPcLatitude() { // onchange
var funcid = "get_postcode_latitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLatitude) {
if (dataLatitude == null) {
//..
} else {
var myLatitude = 0;
for (var i=0;i<dataLatitude.length;i++){
myLatitude = dataLatitude[i].pc_latitude;
}
return parseFloat(myLatitude);
//alert(myLatitude);
}
});
}
function getPcLongitude() { // onchange
var funcid = "get_postcode_longitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLongitude) {
if (dataLongitude == null) {
//..
} else {
var myLongitude = 0;
for (var i=0;i<dataLongitude.length;i++){
myLongitude = dataLongitude[i].pc_longitude;
}
return parseFloat(myLongitude);
//alert(myLongitude);
}
});
}
function getTop5Postcode() { // onchange
setTimeout(function() {
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var latitude = getPcLatitude();
var longitude = getPcLongitude();
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}, 0);
}
Form some reason the
var latitude = getPcLatitude();
var longitude = getPcLongitude();
parts don't work / don't get a value form the functions. When I change the return in both functions into an alert() it does give me the expected values, so those two functions work.
When I set the two variables directly, like so:
var latitude = 5215;
var longitude = 538;
then the getTop5Postcode() function does work and fills the table.
Any help on this?
Regards, Bart
Do not forget that JavaScript is asynchronous, so by the time you reach the return statement, the request is probably not done yet. You can use a promise, something like:
$.getJSON(....).then(function(value){//do what you want to do here})
Both your functions (getPcLatitude and getPcLongitude) are returning nothing because the return statement is inside a callback from an asynchronous request, and that's why an alert show the correct value.
I would suggest you to change both methods signature adding a callback parameter.
function getPcLatitude(callback) {
...
}
function getPcLongitude(callback) {
...
}
And instead of returning you should pass the value to the callback:
callback(parseFloat(myLatitude));
callback(parseFloat(myLongitude));
And your last function would be somehting like that:
function getTop5Postcode() { // onchange
setTimeout(function() {
var latitude;
var longitude;
getPcLatitude(function(lat) {
latitude = lat;
getTop5(); // Here you call the next function because you can't be sure what response will come first.
});
getPcLongitude(function(longi) {
longitude = longi;
getTop5();
});
function getTop5() {
if (!latitude || !longitude) {
return; // This function won't continue if some of the values are undefined, null, false, empty or 0. You may want to change that.
}
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}
}, 0);
}
Of course, this is far away from the perfect solution for your problem but it should work!
And I did not test this code.
I solved this by doing some extra stuff in mysql queries. Now I only have to use the main function.
Things work now! Thanks for all the help!
I am trying to create a simple chrome extension. When a user clicks a checkbox a few datas are send to the background script and from there to the popup. The data is transmitted successfully and it is stored in localstorage at popup
$(document).ready(function() {
chrome.runtime.sendMessage({
from: 'popup',
subject: 'getmessage',
}, function(response) {
for (var x = 0; x < JSON.parse(response).length; x++) {
localStorage.setItem(JSON.parse(response)[x].acnumber, JSON.stringify(JSON.parse(response)[x]));
}
});
for (var i = 0, len = localStorage.length; i < len; i++) {
var datas = JSON.parse(localStorage.getItem(localStorage.key(i)));
var value = datas;
console.log(value);
$('table').append('<tr class="' + value.acnumber + '"><td>' + value.acnumber + '</td><td>' + value.name + '</td><td>' + value.amount + '</td></tr>')
}
})
The problem is that i have to open the popup twice to see the data (appended to the table). The loop is executing before the datas are added to the localstorage
You'll need to move the append table code inside the response function if you want to process the data right after the response callback is fired. Since you mentioned you need the data on multiple pages, you can move the chrome.runtime.sendMessage in its own function and call it only if you don't already have the data. Something like
function getMessage() {
chrome.runtime.sendMessage({
from: 'popup',
subject: 'getmessage',
}, function(response) {
localStorage['haveMessage'] = true;
for (var x = 0; x < JSON.parse(response).length; x++) {
localStorage.setItem(JSON.parse(response)[x].acnumber, JSON.stringify(JSON.parse(response)[x]));
}
processMessage();
});
}
function processMessage() {
for (var i = 0, len = localStorage.length; i < len; i++) {
var datas = JSON.parse(localStorage.getItem(localStorage.key(i)));
var value = datas;
console.log(value);
$('table').append('<tr class="' + value.acnumber + '"><td>' + value.acnumber + '</td><td>' + value.name + '</td><td>' + value.amount + '</td></tr>')
}
}
if (locaStorage['haveMessage']) {
processMessage();
} else {
getMessage();
}
function Controles(contro, nomtab, numtab, action, nomcla, tipdat, lista, datos) {
$(document).on('click', '.'+contro+' #IZQTOD', function(event) {
$.getJSON(action+'&rows='+rows+'&page=1', function(datos) {
var nuevafila;
$.each(datos+tipdat, function(index, data) {
nuevafila = nuevafila + "<tr class='Fila-Grid-"+nomcla+"' id='" + numtab + (index + 1) + "'>";
nuevafila = nuevafila + "<td class='Columna1'>" + (index + 1) + "</td>";
var list = lista.split("-");
for (var j = 1; j < list.length; j++) {
nuevafila = nuevafila + "<td class='Borde-'>" + data+list[j] + "</td>";
}
nuevafila = nuevafila + "</tr>";
});
$('#'+nomtab+' tr:eq(1)').after(nuevafila);
});
});
}
I want to run this piece of code as a function of javascript in order to reuse code.
The part that does not work for me is the part of each:
$. each (+ tipdat data, function (index, data) {
Where "datos" is an object with variables (set and get) (codcli, name, apepat)
I mean to call codcli I do:
$. each (datos.codcli, function (index, data) {
}
But this way is static. I want to do through dynamic parameters.
So the question is how to pass parameters to successfully achieve? Or is that you can not do? There will always be static?
in the code above what I want to do is, but obviously does not work:
tipdat=".codcli"
$. each (datos+tipdat, function (index, data) {
}
I think you're looking for bracket notation.
var tipdat = "codcli";
$.each(datos[tipdat], function (index, data) {
//...
});
Is the same as:
$.each(datos.codcli, ...
If your string has multiple properties, I would do something like this:
var tipdat = "codcli.cod";
var objToIterate = datos;
var parts = tipdate.split('.');
for(var i = 0; i< parts.length; i++) {
objToIterate = objToIterate[parts[i]];
}
$.each(objToIterate, function (index, data) {
//...
});