Function not running on setInterval - javascript

I’m trying to update values in a table pulled in from MySQL but the function is not re-running?
Alternatively, if there is another solution to allow me to update the values from the MySQL database on a 60 second interval please let me know.
EDIT: error has been resolved but now i get a new error instead of replacing the mysql value in the table cell it adds new cells into the table what part of the code would need to be changed or added to resolve this?
The code below returns no errors:
<script type="text/javascript">
$(document).ready(function(){
console.log(1+0);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"<td align='center'> <span class='minutes'>00</span>:<span class='seconds'>00</span> </td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
setInterval(updateTable, 10000);
}
})
})
function updateTable() {
console.log(1+1);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
};
</script>

If you format it well you'll see that youre setInterval is inside your function...
You sould place it in the $(document).ready callback function.
$(document).ready(function () {
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"<td align='center'> <span class='minutes'>00</span>:<span class='seconds'>00</span> </td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
// <===== You should place youre set interval here
}
})
});
function updateTable() {
console.log(1 + 1);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
var updateTableInterval = setInterval(updateTable, 10000);
}

It looks like you are calling setInterval(updateTable) from inside updateTable.
You're not calling updateTable from anywhere outside of updateTable, which means the function is never running, and the setInterval is never executed.
To fix, either:
Put your setInterval outside of updateTable, or
Add updateTable() to the end of your script.
I recommend the former.

Instead of using setInterval,
setInterval(updateTable, 10000);
try using setTimeout after you process and update the table:
function updateTable() {
$.ajax({
...
,complete: function(data){
// do something
setTimeout(updateTable, 10000);
...
});
}
This will allow your code to wait for the information to arrive prior to make another request and not be considered a DoS attack.
Let me know if this works for you or not. We can try something else.

Related

Loop a column value in a table using ajax call

I hope you are fine!
I'm new in coding so I'm facing of something without results.
I have this type of code here in JS.
key: 'generateChart2',
value: function generateChart2() {
var self = this;
var Jahr1 = [];
var years1 = "";
for (var i = 0; i < $('#mf123_select_jahr').val().length; i++) {
if (i > 0) years1 += ","
years1 += $('#mf123_select_jahr').val()[i];
}
var postedData1 = {};
postedData1.years1 = years1;
console.log(postedData1);
$.ajax({
url: "data/json.dashboard.php?call=chart2",
data: postedData1,
dataType: 'json',
type: 'POST',
success: function (dataGraph2) {
var trHTML='';
$.each(dataGraph2, function (key, value) {
for (var i in postedData1) {
Jahr1.push(postedData1[i].years1);
}
console.log(postedData1.years1);
trHTML +=
'<tr><td >' + value.Mandant +
'</td><td >' + thousandSepNeu(value.Jahr1, 2) + " €" +
'</td><td >' + value.Growth +
'</td></tr>';
});
$('#dataGraph2').append(trHTML);
}
});
}
The value.Mandant and the value.Growth are doing well. The problem that I have is that the for loop does not work. I need to thr postedData1 to choose whenever the user choose the year to show him the results.
The output of console.log(postedData1); is:
Am I making a mistake? I know that the problem is on the for loop.
Please any advice i would appreciate it.
:)

Update HTML table cell with mysql data rather than adding new cells

there are 2 things I'm trying to achieve both im having issues with.
the 1st is when my function runs on interval it add new cells into the table rather than updating what may currently be there already.
the 2nd, the layout of the table I'm trying to create as 10 columns across 12 rows down where the cells get limited by these measurements rather than displaying all 120 cells at once ( i have not created a CSS or script for this part yet as after looking around the internet i couldn't find a reference as to where to start.)
<script type="text/javascript">
$(document).ready(function(){
console.log(1+0);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"<td align='center'> <span class='minutes'>00</span>:<span class='seconds'>00</span> </td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
setInterval(updateTable, 10000);
}
})
})
function updateTable() {
console.log(1+1);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
/*( i have been told this part is the issue as to why the cells get added rather than updated but im not sure how i need to correct it to resolve this issue)*/
}
}
});
};
</script>
For first tip:
define a Id for row on create rows
var tr_str = "<tr id='"+ beacon +"'>";
So, now you can add or replace depends if exist, on update function;
var $table = $("#userTable tbody");
var $row = $('tr#'+beacon);
if($row.length) $row.replaceWith(tr_str);
else $table.append($newRow);
Avoid searching for specific HTML elements and updating them:
It's always tricky when updating HTML and especially updating specific cells of a table. The more complex your table structure becomes, the harder it is to update. If done right, it can work but it's messy.
The better approach would be to keep in memory your data and to regenerate your table when that data changes.
Example:
function generateFakeData(){
const data = [];
const max = Math.floor(Math.random() * 100);
for(let i = 0; i < max; i++){
const beacon = Math.floor(Math.random() * 100);
const location = Math.floor(Math.random() * 100);
data.push({id: i, beacon, location});
}
return data;
}
const $table = $('#table > tbody');
const data = [];
function start(){
//immediately load data
fetchData();
//load data every 10 seconds
setInterval(fetchData, 1000);
}
function fetchData(){
//Do ajax request here
const response = generateFakeData();
//On success call update data
handleNewData(response);
}
function handleNewData(response){
response.forEach(({id, location, beacon})=>{
const item = data.find(item=>item.id === id);
//if item exists
if(item){
item.location = location;
item.beacon = beacon;
} else {
//item doesn't exist so add it
data.push({id, location, beacon});
}
})
//after data has been updated
//update html
updateTable();
}
function updateTable(){
$table.html(
data.sort((a,b)=>b.id-a.id).map(({id, location, beacon})=>{
return `
<tr>
<td>${id}</td>
<td>${location}</td>
<td>${beacon}</td>
</tr>
`
}).join("")
);
}
//start app
start();
td {
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<thead>
<tr>
<th>#</th>
<th>Location</th>
<th>Beacon</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

call ajax using javascript funtion to update MYSQL result

I have a table the outputs as MYSQL VALUEJAVASCRIPT TIMER
and im looking at re calling the AJAX that sends across the mysql result to update it in the table without restarting the timer.
but i get a unexpected token ) and no matter which way i write it a still get unexpected token line 56 ,I have tried changing it to }); or } and get the same all throughout and if i remove it it says its missing
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"<td align='center'> <span class='minutes'>00</span>:<span
class='seconds'>00</span> </td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
})
});
function updateTable() {
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
var updateTableInterval = setInterval(updateTable, 5000);
});
</script>
Your variable updateTableInterval is inside your AJAX option object. Moves it one line below.
Then, your function updateTable is not closed, so adds a } at the end.
Finally, your $(document).ready anonymous function is not closed either. Adds }) at the very end.
Do not forget to also close your <script> tag.
For the last three points, I said that because your code snippet have not all these. But maybe it is right on your local code.

How to display image from database instead of image path using jQuery

I want to display image from my database which stores the path to the image's location. Following code gives me the image path only in the output. What changes do I need to make in order for image to appear instead of image path?
GetBusinessCategoryList: function () {
debugger;
var data = JSON2.stringify({
});
$.ajax(
{
contentType: "application/json; charset=utf-8",
type: 'POST',
url: 'http://localhost:44719/Modules/BusinessCategoryView/Service/BusinessCategoryWebService.asmx/GetAllBusinessCategory',
dataType: 'json',
data: data,
success: function (result) {
alert("ok");
var returnedData = result;
BusinessManagement.BindBusinessCategoryList(returnedData);
},
error: function (error) {
alert("error");
}
});
},
BindBusinessCategoryList: function (data) {
debugger;
var cLst = data.d;
if (cLst.length > 0) {
headElements += '<table id="customerTable" cellspacing="0" cellpadding="0" >';
headElements += '<thead class="sfHeadingone">';
headElements += '<tr><th align="left">Category Image</th>';
;
headElements += '</thead>';
$('#tblGrid').html(headElements);
var i = 0;
if (i === 0) {
bodyElements += '<tbody>';
}
$.each(cLst, function (index, value) {
bodyElements += "<td>" + value.CategoryImage + "</td>";
}
});
Use img to display an image. Pass the image url to the src attribute of the img tag
bodyElements += "<td><img src='" + value.CategoryImage + "'></td>";

showing error that mouse_id is undefined while implementation in javascript

Hi I am getting an error while implementing the following.
When I click on the "save" button in following code:
<td width="20%"> <input id="save" onClick="updateMouseInfo();" type="button" value="Save" /></td>
I want to call the mouse_id parameter from getMouseInfo() function to updateMouseInfo() and I am getting the error that mouse_id is undefined, so please help me with the solution.
function getMouseInfo(mouse_id)
{
var dataString = {auth_token: sessionStorage.auth_token, id: mouse_id};
var mh_url = MH_HOST + '/mice/get_mouse_info.json';
alert("Inside Mouse Get Info");
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
//for (var info_count = 0, info_len = data.length; info_count < info_len; info_count++ );
//{
alert("Inside for loop");
//var mouse_info = data.cage.mice[info_count];
var ear_tag = document.getElementById("ear_tag");
var age = document.getElementById("age");
var genotype = document.getElementById("genotype");
var owner = document.getElementById("owner");
//var born = document.getElementById("born");
//var euthanize = document.getElementById("euthanize");
//var note = document.getElementById("note");
ear_tag.innerHTML = data[0].ear_tag;
age.innerHTML = data[0].age;
genotype.innerHTML = data[0].genotype_id;
owner.innerHTML = data[0].owner_id;
//born.innerHTML = data[0].dob;
//euthanize.innerHTML = data[0].dob;
//note.innerHTML = data[0].dob;
//}
},
error: function (data)
{
alert("fail");
}
});
}
//update mouse info
function updateMouseInfo(mouseid)
{
var ear_tag = $('#input_ear_tag').val();
var age = $('#input_age').val();
var genotype = $('#input_genotype').val();
var owner = $('#input_owner').val();
var dataString = {auth_token: sessionStorage.auth_token, id: mouseid, mouse:
{ear_tag: ear_tag, age: age,}};
var mh_url = MH_HOST + '/mice/update.json';
alert("Inside Mouse update Info");
console.log('Data String='+ dataString.auth_token + 'Mouse id=' + dataString.id);
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
document.getElementById('ear_tag').innerHTML = "<div" + ear_tag + "'>" + ear_tag + "</div>";
document.getElementById('age').innerHTML = "<div" + age + "'>" + age + "</div>";
document.getElementById('genotype').innerHTML = "<div" + genotype + "'>" + genotype + "</div>";
document.getElementById('owner').innerHTML = "<div" + owner + "'>" + owner + "</div>";
},
error: function (data)
{
alert("fail");
}
});
}
I am getting the following error in the browser console.
m_id=99
Data String=pvHxzkr3cys1gEVJRpCDMouse id=undefined
Whereas the id should be 99 in the above case it is showing undefined.
You are calling the updateMouseInfo function in the following manner:
onClick="updateMouseInfo();"
if you want to have same mouseid value which is taken by getMouseInfo() function when you call updateMouseInfo(),you will have to globalize getMouseInfo()
Hope it works.

Categories