Setting something in DB only once - javascript

I'm using a setInterval to detect a value I get from my PLC(Programmable logic controller) When it is 1 it executes a PHP page that inserts data in my MYSQL database.
So when I'm holding my button down for longer than 1 second, it sets the DB values multiple times in it.
Below you can find my code:
var Axo800RstBtn;
setInterval(function()
{
Axo800RstBtn = document.getElementById('Axo800BtnStatus').innerHTML;
var BatchUnits1 = document.getElementById('Axo800BatchProduction').innerHTML;
if(Axo800RstBtn == 1)
{
$.ajax({
method: "POST",
url: "SetBatchProductionInDB.php",
data: {
machineNumber: 1,
actualProduction: BatchUnits1
}
})
.done(function(msg)
{
console.log("Bericht: " + msg);
})
}
},1250);
Is there a way to tell my page it can only execute once per 1 minute? some kind of block. Or maybe a block on the execute query?

This could do the trick:
var Axo800RstBtn;
var hasBeenSet = false;
setInterval(function()
{
Axo800RstBtn = document.getElementById('Axo800BtnStatus').innerHTML;
var BatchUnits1 = document.getElementById('Axo800BatchProduction').innerHTML;
if(Axo800RstBtn == 1 && !hasBeenSet)
{
hasBeenSet = true;
$.ajax({
method: "POST",
url: "SetBatchProductionInDB.php",
data: {
machineNumber: 1,
actualProduction: BatchUnits1
}
})
.done(function(msg)
{
console.log("Bericht: " + msg);
})
}
},1250);
Although I would strongly advise that you also do this control server-side. I.E. you could keep track of the script being called by setting up a session var in PHP.
This code will prevent the request from being sent as soon as the request has been sent once. If you want to enable it after 60 seconds you could add after hasBeenSet = true;
hasBeenSet = true;
setTimeout(function(){ hasBeenSet = false}, 60000);

Related

Getting logic error using JavaScript on creating like/dislike counter

I've fixed the bug. I'm documenting my code for future reference.
I'm creating a like/dislike counter and getting a logic error.
My script works such that on clicking on either button I can like/dislike or undo that action. I've tried creating logic such that when I dislike after liking the post, or vice versa, the dislike decrements and the like counter increments . The problem where I'm stuck at is after successively clicking both buttons, either one of the counter resets to zero.
<script type="text/javascript">
var dislike_b = like_b = false;
var num1 = 0;
var like = parseInt("{{post.like_votes}}");
var num2 = 0;
var dislike = parseInt("{{post.dislike_votes}}");
function likeHandler() {
const xhr = new XMLHttpRequest();
if (dislike_b == true){
dislikeHandler();
//dislike_b = false ;
}
// like iterator
like = like + (-1)**num1 ;
num1 = (num1 + 1)%2;
document.getElementById("like").innerHTML = like;
like_b = !like_b;
console.log( like , num1);
//var catid;
//catid = $(this).attr("data-catid");
$.ajax(
{
type: "POST",
url: "/likepost/",
data: {
//post_id: catid ,
votes : like ,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
//$('#like' + catid).remove();
$('#message').text(data);
}
})
}
function dislikeHandler() {
const xhr2 = new XMLHttpRequest();
if (like_b == true){
likeHandler();
}
// like iterator
dislike = dislike + (-1)**num2 ;
num2 = (num2 + 1)%2;
document.getElementById("dislike").innerHTML = dislike;
dislike_b = !dislike_b;
console.log( dislike , num1);
$.ajax(
{
type: "POST",
url: "/dislikepost/",
data: {
votes : dislike ,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
$('#message').text(data);
}
})
}
</script>
Have you tried preventDefault()?
You could try simplifying it a little like this by putting the ajax request in its own function. What else needs to happen when clicking the buttons? Just comment and I'll update.
// Variables
let likes = 0
let dislikes = 0
// Like
function like() {
const likeDOMText = document.querySelector('.like span')
likes++
likeDOMText.innerText = likes
// Calling the ajax request
initRequest({
likes: likes,
dislikes: dislikes,
// And whatever else
})
}
// Dislike
function dislike() {
const dislikeDOMText = document.querySelector('.dislike span')
dislikes++
dislikeDOMText.innerText = dislikes
// Calling the ajax request
initRequest({
likes: likes,
dislikes: dislikes,
// And whatever else
})
}
// Ajax request to server
function initRequest(data) {
// $.ajax({
// ...
//data: JSON.parse(data)
//})
}
<button class="like" onclick="like()">Like <span>0</span></button>
<button class="dislike" onclick="dislike()">Dislike <span>0</span></button>

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

Global variable update AJAX POST

Below is my full JS file beginning to end. I set a variable 'rendered' outside all functions. Then, since it is required in the if check just before issuing a POST request I want to use it as flag and update it's value to be true upon post request completion. The issue is that all the console.log calls do print the changed value but it does not persist. When again the position coordinates are fetched automatically in the watchPosition function, calculateDistance function is invoked again. Then, the previous saved value with "window.rendered = true" is not there, it is actually false and it enters the if condition. How can I achieve the goal of not issuing the post request again until another post request changes this flag variable back to false?
var rendered = false;
function myfunc() {
rendered = true;
console.log(window.rendered);
}
function updatePosition() {
if(navigator.geolocation) {
navigator.geolocation.watchPosition(calculateDistance);
}
else {
console.log("Geolocation is not supported by this browser.")
}
}
function calculateDistance(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var target = new google.maps.LatLng(55.85365783555865, -4.288739944549508);
var dis = google.maps.geometry.spherical.computeDistanceBetween(pos, target);
console.log(window.rendered);
var self = this;
if(dis <= 1000 && dis >= 0 && window.rendered == false) {
console.log("Distance"+dis);
var url = '/dogpark/near_park/';
var csrftoken = getCookie('csrftoken');
$.ajax({
url: url,
type: "POST",
data: {
csrfmiddlewaretoken: csrftoken,
in_proximity : 1
},
async: false,
success: function(data) {
myfunc();
self.rendered = true;
window.rendered = true;
alert(window.rendered);
window.location = '/dogpark/near_park/';
},
complete: function(data) {
console.log("Trying");
window.rendered = true;
alert(window.rendered);
},
error: function(xhr, errmsg, err) {
console.log(xhr.status+": "+xhr.responseText);
},
});
}
window.onload = updatePosition()
A simple way is to use another variable to track the ajax call completion. So that you don't make another Ajax call until the previous one returns a repsonse(success/failure).
var isWaitingForResponse = false;
...
function calculateDistance(position) {
...
if(dis <= 1000 && dis >= 0 && window.rendered == false && !isWaitingForResponse) {
isWaitingForResponse = true;
...
success: function(data) {
isWaitingForResponse = false
...
},
complete: function(data) {
isWaitingForResponse = false
...
},
error: function(xhr, errmsg, err) {
isWaitingForResponse = false
...
}
...

Ajax if more then one #mention

I am trying to make a facebook and twitter style mention system using jquery ajax php but i have a problem if i try to #mention more then one user. For example if i start to type something like the follow:
Hi #stack how are you.
The results showing #stack but if i try to mention another user like this:
Hi #stack how are you. i am #azzo
Then the results are nothing. What i am missing my ajax code anyone can help me please ?
I think there is a regex problem for search user_name. When i write some username after first one like #stack then the ajax request posting this:
f : smen
menFriend : #stack
posti : 102
But if i want to tag my other friend in the same text like this:
Hi #stack how are you. I am #a then ajax request looks like this:
f : smen
menFriend : #stack, #a
posti : 102
So what I'm saying is that apparently, ajax interrogates all the words that begin with #. It needs to do is interrogate the last #mention from database.
var timer = null;
var tagstart = /#/gi;
var tagword = /#(\w+)/gi;
$("body").delegate(".addComment", "keyup", function(e) {
var value = e.target.value;
var ID = e.target.id;
clearTimeout(timer);
timer = setTimeout(function() {
var contents = value;
var goWord = contents.match(tagstart);
var goname = contents.match(tagword);
var type = 'smen';
var data = 'f=' +type+ '&menFriend=' +goname +'&posti='+ID;
if (goWord.length > 0) {
if (goname.length > 0) {
$.ajax({
type: "POST",
url: requestUrl + "searchuser",
data: data,
cache: false,
beforeSend: function() {
// Do Something
},
success: function(response) {
if(response){
$(".menlist"+ID).show().html(response);
}else{
$(".menlist"+ID).hide().empty();
}
}
});
}
}
}, 500);
});
Also here is a php section for searching user from database:
$searchmUser = mysqli_real_escape_string($this->db,$searchmUser);
$searchmUser=str_replace("#","",$searchmUser);
$searchmUser=str_replace(" ","%",$searchmUser);
$sql_res=mysqli_query($this->db,"SELECT
user_name, user_id
FROM users WHERE
(user_name like '%$searchmUser%'
or user_fullname like '%$searchmUser%') ORDER BY user_id LIMIT 5") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($sql_res,MYSQLI_ASSOC)) {
// Store the result into array
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
Looks like you're sending an array which is result of match you in AJAX request.
Though I cannot test it but you can use a lookahead in your regex and use 1st element from resulting array. Negative lookahead (?!.*#\w) is used to make sure we match last element only.
var timer = null;
var tagword = /#(\w+)(?!.*#\w)/;
$("body").delegate(".addComment", "keyup", function(e) {
var value = e.target.value;
var ID = e.target.id;
clearTimeout(timer);
timer = setTimeout(function() {
var contents = value;
var type = 'smen';
var goname = contents.match(tagword);
if (goname != undefined) {
var data = 'f=' +type+ '&menFriend=' +goname[1] +'&posti='+ID;
$.ajax({
type: "POST",
url: requestUrl + "searchuser",
data: data,
cache: false,
beforeSend: function() {
// Do Something
},
success: function(response) {
if(response){
$(".menlist"+ID).show().html(response);
} else {
$(".menlist"+ID).hide().empty();
}
}
});
}
}, 500);
});

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

Categories

Resources