Json table update after certain date - javascript

At the moment i have this code
// JavaScript Document
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'https://api.import.io/store/data/93296dfc-1edb-4aa6-a3e5-2207fa52f3ea/_query?input/webpage/url=http%3A%2F%2Fwww.seatwave.com%2Fthe-script-tickets%2Fseason&_user=687c839c-f236-4817-90c9-f6eb81334c2a&_apikey=pvXHYMTbZD3Za3TB%2Bn8LgVybPltV1a379yBNfSfzepw2piIhs%2FxHinVseH7G4BwItVQ57aNJnyk6g6g%2BAxyEMg%3D%3D',
success: function (json) {
//var json = $.parseJSON(data);
for(var i =0;i < json.results.length;i++) {
var title = json.results[i].name;
var venue = json.results[i].venue;
var date = json.results[i].date;
var button = "<button class='btn btn-info' data-url='"+(i+1)+".html'>Compare</button>";
$("#apple").append("<tbody><tr><td>"+title+"</td><td>"+venue+"</td><td>"+date+"</td><td>"+button+"</td></tr></tbody>");
$("#apple").find(".btn.btn-info").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error: function(error){
console.log(error);
}
});
This appends the URL to a table. However as you can see this code here data-url='"+(i+1)+".html' created the button with an increment of 1 on the amount of buttons listed.
The issue is, this api is updating every 5 hours. When the event passes, The buttons need to really be updated. Otherwise the whole site breaks.
So the question is how could i go around making the links unique and update when an event passes? whilst im writing this i believe i could just use the Date function, So the code would be
data-url='"+date+".html'
Any other suggestions would be great?

There are many ways you could do this. The easiest would be to add a meta tag to the page that forces it to refresh each 5 hours. If for some reason you need to do it with code, then you'll need to add a timer that checks for updates and refreshes the button data. A working example of that is shown below. The data does have a time stamp, but it's set to the far future. So rather than check that the code simply updates each 10 seconds (you can set to whatever frequency you need).
<html>
<body>
<style type="text/css">
table { border-collapse: collapse; font-family: sans-serif; font-size: 12px;}
table td { border: 1px gray dotted; padding: 2px;background-color:aliceblue;}
table caption {font-weight: bold; color: firebrick;}
</style>
<table id="apple"><caption></caption><tbody></tbody></table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
var lastUpdate;
function update() {
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'https://api.import.io/store/data/93296dfc-1edb-4aa6-a3e5-2207fa52f3ea/_query?input/webpage/url=http%3A%2F%2Fwww.seatwave.com%2Fthe-script-tickets%2Fseason&_user=687c839c-f236-4817-90c9-f6eb81334c2a&_apikey=pvXHYMTbZD3Za3TB%2Bn8LgVybPltV1a379yBNfSfzepw2piIhs%2FxHinVseH7G4BwItVQ57aNJnyk6g6g%2BAxyEMg%3D%3D',
success: function (json) {
/*
Removed - data time stamp does not appear to be useful
if (json.results[0].date == lastUpdate) return;
lastUpdate = json.results[0].date;
$("#apple caption").html( 'Last Updated: ' + lastUpdate );
*/
$("#apple caption").html( "Last Updated: " + (new Date()).toString() );
$("#apple tbody").html( "" );
for(var i =0;i < json.results.length;i++) {
var title = json.results[i].name;
var venue = json.results[i].venue;
var date = json.results[i].date;
var button = "<button class='btn btn-info' data-url='"+(i+1)+".html'>Compare</button>";
$("#apple tbody").append("<tr><td>"+title+"</td><td>"+venue+"</td><td>"+date+"</td><td>"+button+"</td></tr>");
$("#apple").find(".btn.btn-info").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error: function(error){
console.log(error);
}
});
}
update();
var timerId = setInterval( update, 10000 );
</script>
</body>
</html>

Related

JQUERY ajax post - multiple click, one reload - it is possible?

I have a problem and I don't know what is the solution. I would like to reload the specified divs only once after multiple click. Now when I add new item to the database from dropdown input, then after each click each time reload the specified div, and sometimes it is very disturbing. When you want to select a new item from the list, and then suddenly reset, and you need to select again). How can I do that if I click to add new item (sometimes I select 4-5 new items - not multiple select!) then not refresh the specified div after each click, just once with a specified delay.
Here is the current code of the javascript part (now it refresh after 100 milliseconds after a new item added). I hope that someone could help me, or give me an idea how can I resolve this. Many thanks!
<script type="text/javascript">
$('body').on('click',".addhplayer",function() {
var absidplayer = $('#abshidplayer').find(":selected").val();
var abstype = $('#abshtype').find(":selected").val();
var obj = $(this); // first store $(this) in obj
var absseasonid = $(this).attr('data-absseasonid');
var absidclub = $(this).attr('data-absidclub');
var absidmatch = $(this).attr('data-absidmatch');
//var dataString = 'abstype=' + abstype + '&addplayer=1&' + 'absidplayer=' + absidplayer + '&' + 'absidclub=' + absidclub + '&' + 'absidmatch=' + absidmatch + '&' + 'absseasonid=' + absseasonid;
$.ajax({
url: 'edit_absence.php',
type: 'POST',
timeout: 100,
data: {
addtype: abstype,
addhplayer: '1',
addidplayer: absidplayer,
addidclub: absidclub,
addidmatch: absidmatch,
addseasonid: absseasonid
},
success: function(response, textStatus, jqXHR){
$('.hpstatus').show();
$(".hpstatus").load(" .hpstatus");
$('#injur').show();
$("#injur").load(" #injur");
$("#homelineups").load(" #homelineups");
$("#awaylineups").load(" #awaylineups");
},
});
});
</script>
check out my old response to this question :
How do you send an ajax request every time that a form input field changes?
basically wrap your event code to a delayed function, on multiple call it will cancel the previous planned ajax call if the delay is not reach
edit > on your particular code :
var changeTimer = false;
function yourSpecificEventCode(){
var absidplayer = $('#abshidplayer').find(":selected").val();
var abstype = $('#abshtype').find(":selected").val();
var $o = $(this); // first store $(this) in obj
var absseasonid = $o.attr('data-absseasonid');
var absidclub = $o.attr('data-absidclub');
var absidmatch = $o.attr('data-absidmatch');
$.ajax({
url: 'edit_absence.php',
type: 'POST',
timeout: 100,
data: {
addtype: abstype,
addhplayer: '1',
addidplayer: absidplayer,
addidclub: absidclub,
addidmatch: absidmatch,
addseasonid: absseasonid
},
success: function(response, textStatus, jqXHR){
$('.hpstatus').show().load(" .hpstatus");
$('#injur').show().load(" #injur");
$("#homelineups").load(" #homelineups");
$("#awaylineups").load(" #awaylineups");
},
});
}
$('body').on('click',".addhplayer",function() {
if(changeTimer !== false) clearTimeout(changeTimer);
let t = this ;
changeTimer = setTimeout(function(){
yourSpecificEventCode.call( t ) ;
changeTimer = false;
},300);
});

Live Data Feed and Scrollbar Position

I am retrieving data from a MySQL database and displaying it on a website using the EventSource API. So far everything is working as expected, but I want to display the data in a fixed height div, and fix the scrollbar to the bottom of this div - i.e always show the latest feed results first.
Now when I load the page the scrollbar is fixed to the top.
I have tried the suggestion here but it doesn't seem work. Is it because I am working with live data and AJAX requests in order to populate the div?
My cose so far is;
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<style type="text/css">
#result {
overflow: auto;
max-height:224px;
width: 500px;
}
</style>
<script type="text/javascript">
// scrollbar to bottom
$("document").ready(function(){
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
});
// retrieve data from server and display in div
$("document").ready(function(){
var source = new EventSource("data.php");
var offline;
$.ajax({
type: "POST",
url: 'data.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
$.each(data, function(key, value) {
document.getElementById("result").innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
} // end success
});
});//end dom ready
</script>
</head>
<body>
<div id="result"><!--Server response inserted here--></div>
</body>
</html>
The strange this is, whenever I remove the live feed javascript and manually add some (lorem ipsum) text into the <div id="result"> it works, the scrollbar appears at the bottom of the div.
I could be doing something very silly :)
Any advice is appreciated.
When you load more data via ajax, the size of the content will change. Have you tried setting the scroll again after you've rendered the content? i.e.:
success: function(data){
var objDiv = document.getElementById("result");
$.each(data, function(key, value) {
objDiv.innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
objDiv.scrollTop = objDiv.scrollHeight;
} // end success
});
Thus setting the scroll value the same way you do when the page loads.
Alternatively, here's another completely different option:
If you want the most recent values to be most prominent, you could simply output them in reverse order, so the newest ones are at the top of the div, where the user will see them first. You can use jQuery's .prepend() method to add content to the beginning of the div, above the previous results. Then there's no need for messing about with scrolling. http://api.jquery.com/prepend/ I'd argue this is more user-friendly, but it's up to you obviously.
I'm not 100% sure about this but one issue that I see is that you're making an asynchronous AJAX call to the server after you scroll to the bottom of the div.
Maybe try something along the lines of this:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<style type="text/css">
#result {
overflow: auto;
max-height:224px;
width: 500px;
}
</style>
<script type="text/javascript">
// retrieve data from server and display in div
$("document").ready(function(){
var source = new EventSource("data.php");
var offline;
$.ajax({
type: "POST",
url: 'data.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
$.each(data, function(key, value) {
document.getElementById("result").innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
} // end success
});
});//end dom ready
</script>
</head>
<body>
<div id="result"><!--Server response inserted here--></div>
</body>
</html>
Explanation: The div gets populated after you scroll to the bottom of it. Therefore when the scrolling is executed the scrollHeight property is still at the original height value of the div. Now, if you execute the scroll action after you populate the div, it should work fine.
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
that code doesn't say "anchor" the scrollbar to the bottom, it just says scroll down the actual height of the div once, but since you put this code before your ajax request, your div must be empty, so just put theese two lines at the end of your ajax "success" function.
success: function(data){
$.each(data, function(key, value) {
document.getElementById("result").innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
}
It was just small line which you were missing, please add below code
$.ajax({
type: "POST",
url: 'data.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
var objDiv = document.getElementById("result");
$.each(data, function(key, value) {
objDiv.innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
objDiv.scrollTop = objDiv.scrollHeight;
} // end success
});

How can I refresh the append data without page refresh jquery?

I am trying to use ++ in jquery to append data, and I face a problem, I need to refresh the value again if I click other button without refresh page, how can I do that? The var count will increase as I clicked, I want to know if I can start over this count again when I click second button.
var count='1';
$('#good').on('click',function(){
$.ajax({
url: MyAjaxSearch.ajaxurl,
type:'POST',
cache: false,
data:data,
success: function(data){
count++
}
});
}):
$('#second').on('click',function(){
//refresh the var count, start from 1 again
count++
});
Updated Answer (based on clarification from OP):
I want to if I can start over this count again when I click second button
$('#second').on('click',function(){
//refresh the var count, start from 1 again
count = 1;
});
Live Example:
var count = 1;
$('#good').on('click', function() {
count++;
snippet.log("Incremented, count = " + count);
});
$('#second').on('click', function() {
//refresh the var count, start from 1 again
count = 1;
snippet.log("Reset, count = " + count);
});
<input type="button" id="good" value="Increment">
<input type="button" id="second" value="Reset">
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Or if you wanted the first incremented number to be 1, start with count = 0:
Live Example:
var count = 0;
$('#good').on('click', function() {
count++;
snippet.log("Incremented, count = " + count);
});
$('#second').on('click', function() {
//refresh the var count, start from 0 again
count = 0;
snippet.log("Reset, count = " + count);
});
<input type="button" id="good" value="Increment">
<input type="button" id="second" value="Reset">
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Original Answer:
I'm going to take a total guess at it here and say that in your ajax callback, you're modifying the page in some way, for instance:
$('#good').on('click', function() {
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function(data) {
$("selector-for-some-elements").html("new content"); // <===
current_page++
}
});
});
And that you want a click on the other element to reset things back to the way they were when the page was first loaded.
If so, then you can do something like this (see comments):
var current_page = '1';
// *** A variable for remembering the original content
var originalContent;
$('#good').on('click', function() {
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function(data) {
// Grab the elements we're going to change
var elementsToChange = $("selector-for-elements");
// If we don't have saved content...
if (!originalContent) {
// Save the original content
originalContent = elementsToChange.clone();
}
// Modify it
elementsToChange.html(/*....*/);
current_page++
}
});
});
$('#second').on('click', function() {
// If we have original content...
if (originalContent) {
// Put it back
$("selector-for-some-elements").replaceWith(originalContent);
current_page = 1;
}
});
Obviously, many aspects of the above would vary based on what you're actually trying to do, but as you haven't told us what that is, this is the best I can do...

Speed Up Jquery heartbeats

I'm a pretty new programmer who made an application that sends out a heartbeat every 3 seconds to a php page and returns a value, the value of which decides which form elements to display. I've been fairly pleased with the results, but I'd like to have my jquery as fast and efficient as possible (its a little slow at the moment). I was pretty sure SO would already have some helpful answers on speeding up heartbeats, but I searched and couldn't find any.
So here's my code (just the jquery, but I can post the php and html if needed, as well as anything anyone needs to help):
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$('.jcontainer').each(function() {
var $e = $(this);
var dataid = $e.data("param").split('_')[1] ;
$.ajax({
url: 'heartbeat.php',
method: 'POST',
contentType: "application/json",
cache: true,
data: { "dataid": dataid },
success: function(data){
var msg = $.parseJSON(data);
if (msg == ""){ //after reset or after new patient that is untouched is added, show checkin
$e.find('.checkIn').show();
$e.find('.locationSelect').hide();
$e.find('.finished').hide();
$e.find('.reset').hide();
}
if ((msg < 999) && (msg > 0)){ // after hitting "Check In", Checkin button is hidden, and locationSelect is shown
$e.find('.checkIn').hide();
$e.find('.locationSelect').show();
$e.find('.finished').hide();
$e.find('.reset').hide();
$e.find('.locationSelect').val(msg);
}
if (msg == 1000){ //after hitting "Checkout", Option to reset is shown and "Finished!"
$e.find('.checkIn').hide();
$e.find('.locationSelect').hide();
$e.find('.finished').show();
$e.find('.reset').show();
}
}
});
});
},3000);
$('.checkIn').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "checkin.php",
// Data used to set the values in Database
data: { "checkIn" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.locationSelect').show();
$container.find('.locationSelect').val(1);
}
});
});
$('.reset').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "reset.php",
// Data used to set the values in Database
data: { "reset" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.checkIn').show();
}
});
});
$('.locationSelect').change(function(e) {
if($(this).children(":selected").val() === "CheckOut") {
$e = $(this);
var data = $e.data("param").split('_')[1] ;
$.ajax({
type: "POST",
url: "checkout.php",
// Data used to set the values in Database
data: { "checkOut" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.finished').show();
$container.find('reset').show();
}
});
}
else{
$e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of select (1 for the first select)
// You can map this to the corresponding select in database...
$.ajax({
type: "POST",
url: "changeloc.php",
data: { "locationSelect" : $(this).val(), "selectid" : data},
success: function() {
// Do something here
}
});
}
});
});
</script>
Thanks for all and any help! Please just ask if you need any more details! Thanks!
Alot of factors could be causing slowness. Some things to consider:
The speed of the heartbeat is not dependent on your client-side javascript code alone. There may be issues with your server-side php code.
Also, a heartbeat every three seconds is very frequent, perhaps too frequent. Check in your browser's developer debug tools that each of the requests is in fact returning a response before the next 3 second interval. It could be that your server is slow to respond and your requests are "banking up".
You could speed your your jQuery a fraction by streamlining your DOM manipulation, eg:
if (msg == "")
{
$e.find('.checkIn').show();
$e.find('.locationSelect, .finished, .reset').hide();
}

Refresh $(document).ready in JavaScript

I have a script that runs continuously on my page, and it detects if a new item has been submitted to my database, at which point it adds additional html to my page:
var count_cases = -1;
setInterval(function(){
$.ajax({
type : "POST",
url : "new_lead_alerts_process.php",
dataType: 'json',
cache: false,
success : function(response){
$.getJSON("new_lead_alerts_process.php", function(data) {
if (count_cases != -1 && count_cases != data.count) {
//add new HTML element to page
$('#content').prepend("<div class=\"reportRow\"><div id=\"reportRowLeft\" style=\"width: 63px;\">"+dayOfMonth+"</div><div id=\"reportRowCenter\">"+timeSubmitted+"</div><div id=\"reportRowRight\" style=\"width: 126px;\"><div id=\"claimButton"+data.id+"\"><form action=\"\" method=\"post\" name=\""+data.id+"\"><input type=\"hidden\" id=\"lead_id"+data.id+"\" name=\"lead_id\" value=\""+data.id+"\" /><input type=\"hidden\" id=\"client_id"+data.id+"\" name=\"client_id\" value=\""+data.client_id+"\" /><input type=\"hidden\" id=\"user_id"+data.id+"\" name=\"user_id\" value=\"1\" /><input type=\"image\" name=\"submit\" class=\"claimButton\" onClick=\"expand('claimed"+data.id+"');collapse('claimButton"+data.id+"');\" src=\"images/claim.gif\" id=\""+data.id+"\" style=\"width: 126px; height: 29px; margin: 0; border: 0px; padding: 0; background: none;\"></form></div><img id=\"claimed"+data.id+"\" style=\"display: none;\" src=\"images/claimed.gif\" /></div><div id=\"clear\"></div></div>");
}
count_cases = data.count;
});
}
});
},1000);
I have another script that submits an update to the database via AJAX when a user clicks a button in the newly created element. It looks like this:
//update db when lead is claimed
$(document).ready(function(){
$(".claimButton").click(function(){
var element = $(this);
var Id = element.attr("id");
var client_id = $("#client_id"+Id).val();
var user_id = $("#user_id"+Id).val();
var lead_id = $("#lead_id"+Id).val();
var dataString = 'client_id='+client_id+'&user_id='+user_id+'&lead_id='+lead_id;
$.ajax({
type: "POST",
url: "new_lead_alerts_update.php",
data: dataString,
cache: false
});
return false;});
});
My issue, is that the second AJAX submit doesn't appear to be working. I think this is due to the fact that the $(document).ready command only fires when the page first loads, and due to the fact that I'm updating the page content dynamically via AJAX, any new elements added to the page can't be submitted.
I've tried .delegate and .live, as opposed to .ready and neither appeared to work.
Any help would be greatly appreciated.
Make the functionality from document.ready into a callback, and then do that every time you append a new element to the page from ajax like this:
$(document).ready(function(){ MakeClaim(); });
function MakeClaim(){
$(".claimButton").click(function(){
var element = $(this);
var Id = element.attr("id");
var client_id = $("#client_id"+Id).val();
var user_id = $("#user_id"+Id).val();
var lead_id = $("#lead_id"+Id).val();
var dataString = 'client_id='+client_id+'&user_id='+user_id+'&lead_id='+lead_id;
$.ajax({
type: "POST",
url: "new_lead_alerts_update.php",
data: dataString,
cache: false
});
return false;});
}
success : function(response){
$.getJSON("new_lead_alerts_process.php", function(data) {
if (count_cases != -1 && count_cases != data.count) {
//that huge string
MakeClaim();
}
count_cases = data.count;
});
}
EDIT
try changing this:
onClick=\"expand('claimed"+data.id+"');collapse('claimButton"+data.id+"');\"
to
onClick=\"expand('claimed"+data.id+"');collapse('claimButton"+data.id+"');return false;\"
Please try this:
function TryIt(getId)
{
var element = $(getId);
var Id = element.attr("id");
var client_id = $("#client_id"+Id).val();
var user_id = $("#user_id"+Id).val();
var lead_id = $("#lead_id"+Id).val();
var dataString = 'client_id='+client_id+'&user_id='+user_id+'&lead_id='+lead_id;
$.ajax({
type: "POST",
url: "new_lead_alerts_update.php",
data: dataString,
cache: false
});
}
just use javascript onclick function in claimButton and call TryIt() function whenever you want.

Categories

Resources