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.
Related
I have problem inserting modal button inside my html table. I'm using AJAX and append built in function. I tried this approach
" Open modal"
but it did'nt work. I tried to remove the button properties like 'class', 'type' , etc and it worked but I need those. Any approach for this. Thank you.
This is my code
<script type=text/javascript>
$(document).ready(function() {
});
function getData(id){
$('#myModal').modal('show');
$.ajax({
type: "GET",
url: "getproducts/",
dataType: 'json',
data: {id: id},
success: function (response) {
var len = 0;
if(response['data'] !=null){
len = response['data'].length;
}
$('#userTable tbody').empty();
if(len > 0){
for(i = 0; i < len; i++) {
var p_id = response['data'][i].p_id;
var p_name = response['data'][i].p_name;
var p_amount = response['data'][i].p_amount;
var m_fname = response['data'][i].m_fname;
var tr_str =
"<tr>" +
"<td>" + p_id + "</td>"+
"<td>" + p_name + "</td>" +
// HOW CAN I ADD MODAL BUTTON HERE THIS APPROACH DOESN'T WORKED
"<td> <button type="button" class="btn btn-primary" data-bs-toggle="modal"
data-bs-target="#myModal2">Open modal</button></td>"
"<tr>";
$('#userTable tbody').append(tr_str);
}
}
}
});
};
</script>
Expected output should be like this
I think the problem with string concatenation
I am giving a code. please replace it.
"<td> <button type='button' class='btn btn-primary' data-bs-toggle='modal'
data-bs-target='#myModal2'>Open modal</button></td>"
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>
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.
This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 8 years ago.
I am creating a small domain availability checker. For that I will parse the desired domain into a form, and submit that to a PHP file with jQuery AJAX.
However while I am looping through the different TLD's it suddenly gets undefined and I am not able to use the "TLD" for further processing within the loop. As far as I can read, it as something to do with the loop happening first and the requests made after, so I somehow have to freeze the index of my array. But I don't know how to do that.
This is my code:
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
}
});
};
return false;
});
The printed console.log's looks like this:
This is a classic JavaScript issue. In the success function (a closure), the i is being used. That callback runs in the future, once the AJAX call is done. By that point, the loop has finished, and i has been incremented to 4.
tlds[4] doesn't exist, and that's why you're getting undefined. The callbacks are all using the same i value.
To fix it, you need to create a new function to capture the value of i for each callback.
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
var createCallback = function(i){
return function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
};
}
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: createCallback(i)
});
};
return false;
});
By the time the ajax calls return, the loop has long since ended, and i has run past the end of tlds. Trying to print tlds[i] is bound to fail.
Break the lookup into a separate function, with local variables that will be valid on the ajax callback:
var checkup = function(datastring, domain, tld) {
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tld + " is " + data);
}
});
};
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
checkup(datastring, domain, tlds[i]);
};
You need to enclose the code in your loop in a closure as follows:
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
for (var i = 0; i < tlds.length; i++ ) {
(function() {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
}
});
})( i );
}
return false;
});
I am new to javascript. I have worked on twitter API. In twitter API i used jQuery.ajax function to get json data from twitter servers. But when i use the same option with google maps server, my app isn't giving any response the moment it enters the jQuery.ajax. I tried to debug it using jslint, but it came out clean. I used debugging using alert, and it stops when it enters jQuery.ajax function. Is meathod to retrieve data varies with the source ?
If not why isn't my code responding ?
Twitter running function ::
var twitterapi = "http://search.twitter.com/search.json?";
jQuery.ajax(
{
type: "GET",
url: twitterapi,
data:
{
"q": hashtag,
"rpp": 1000
},
dataType: 'jsonp'
}).done(function (response)
{
var results = response.results;
for (var i = 0; i < results.length; i++)
{
$("#tweet").prepend("<li class='tweet'>" +
"<img src='" +
results[i].profile_image_url +
"'/>" +
"<span class='username'>" +
results[i].from_user +
"</span> <span class='tweet_content'> " +
results[i].text +
"</span></li>");
}
});
My google maps API(not working)
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
alert("function started");
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
var a =[];
alert("button clickede");
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
alert("making request to" +gurl);
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
alert("request made to"+gurl);
var rows = response.rows;
alert(row[0].elements[0].value);
for(var i=0;i<rows.length;i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = row[i].elements[j].distance.value;
}
}
alert(distance[0][0]);
});
});
});
I don't know what error are you getting so i can't be of much help.
But the code you posted has three issues:
1- Since a is undefined, i couldn't get past the first two lines.
2- Removing the a calls in the code, then it threw a Syntax Error. I fixed this by removing the last }); line.
3- It made the request, but it threw another error (probably because the URL was malformed).