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

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

Related

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

Setting something in DB only once

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

ajax function auto reload

Hello i am getting data from a php file in json format,all works fine.I would however desire that this function reloads every say 3000millisecs thus updating the data.
How do I achieve this?
function loadFbill(hsid)
{
// Display a loading icon in our display element
$('.list-item-display').html('<span><img src="img/progress.gif" /></span>');
// Request the JSON and process it
$.ajax({
type:'GET',
url:""+xhr_path+"js_on.php",
data:"hid="+hsid+"&subscribers=paid",
success:function(feed) {
// Create an empty array to store images
var thumbs = [];
// Loop through the items
for(var i=0, l=feed.response.length; i < l && i < 6; ++i)
{
// Manipulate the image to get thumb and medium sizes
var payee = feed.response[i].result_paid;
var transaction_m = feed.response[i].result_payment_details;
var ptime = feed.response[i].result_time;
var plan = feed.response[i].result_plan;
var payee_num = feed.response[i].result_num;
var localhs = feed.response[i].result_hs;
var transaction_date = feed.response[i].result_payment_date;
var diff_date = feed.response[i].result_time_diff;
// Add the new element to the array
thumbs.push("<div class=list-item><div class=list-datetime><div class=time>"+ptime+"</div></div><div class=list-info><img src=img/pesa/ps_"+transaction_m+".jpg height=28 width=28 class=img-circle img-thumbnail/></div><div class=list-text><a href=# class=list-text-name> "+payee+" </a><p>"+payee_num+" <span class=icon-calendar></span> "+transaction_date+" <span class=icon-calendar-empty></span>"+diff_date+"<span class=icon-globe></span> "+localhs+" </p></div><div class=list-controls> "+plan+"</div></div>");
}
// Display the thumbnails on the page
$('.list-item-display').html(""+thumbs.join('')+"");
// A function to add a lightbox effect
addLB();
},
dataType:'json'
});
}
You can simply add setTimeout into ajax request callback function:
function loadFbill(hsid) {
// Display a loading icon in our display element
$('.list-item-display').html('<span><img src="img/progress.gif" /></span>');
// Request the JSON and process it
$.ajax({
type: 'GET',
url: "" + xhr_path + "js_on.php",
data: "hid=" + hsid + "&subscribers=paid",
success: function (feed) {
// ... all your code untouched
setTimeout(loadFbill, 3000); // <-- and reload again
},
dataType: 'json'
});
}

Loading more posts not working

I am adding a LoadMore function to append more posts based on the length of current displayed posts and total posts in DOM. The issue I am having is when I console log the listofposts and I inspect the element in Google Chrome, I see the length is showing zero (0). I am not sure exactly where I have gone wrong or if the aproach I have taken is right or should I separate the two functions by first loading the first 4 posts, then create a new function separate to handle the appending?
$(document).on('pagebeforeshow', '#blogposts', function() {
//$.mobile.showPageLoadingMsg();
$.ajax({
url: "http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=",
dataType: "json",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() { $.mobile.showPageLoadingMsg(true); },
complete: function() { $.mobile.hidePageLoadingMsg(); },
success:function(data){
var $listofposts = $('data');
console.log($listofposts);
var $loadMore = $listofposts.parent().find('.load-more');
// console.log($loadMore);
currentPage = 0;
postsPerPage = 4;
var showMorePosts = function () {
$offset = currentPage * postsPerPage, //initial value is 0
posts = data.posts.slice($offset, $offset + postsPerPage);
console.log(posts);
$.each(posts, function(i, val) {
//console.log(val);
$("#postlist").html();
var result = $('<li/>').append([$("<h3>", {html: val.title}),$("<p>", {html: val.excerpt})]).wrapInner('');
$('#postlist').append(result);
console.log(result);
});
if(posts.length !== postsPerPage){
alert ('True');
$loadMore.hide();
}
currentPage++;
$("#postlist").listview();
$("#postlist").listview('refresh');
}
showMorePosts();
$loadMore.on('click', showMorePosts);
}});
var $listofposts = $('data');
is asking jQuery for a list of all <data> tags in the document.
You might want to use $(data) instead.

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