Get the number of click counts and call a single ajax call using jquery

38
July 20, 2018, at 11:10 PM

I need to call ajax service when the user continuously clicks a link but Now I have written for a single click. Once clicked ajax called and works fine but continuously clicks means takes only the first click alone. I need how many times clicked totally at the end call ajax service. Any helps greatly appreciated. Here's my code:

 <a href="#" onclick="call()" data-tag="Prev" id="prev"> Prev </a>
function call() {
//Here ajax call function
}

If I click N times means I need N as count and call once ajax function

UPDATE1:

I have tried a timeout for calling the ajax after a period of time while N number of clicks made, stored in count value.Now I needs to call the ajax again same problem happens while appending data error occurs.

$(function () {
    $("#prev").click(function () {
        ++count;
        setTimeout(Previousday(count), 1000); //Set time to wait execute the ajax
        count = 0;
    });
});
Answer 1

You could use a global variable for the click count, and use max authorized clicks to check when you have to send the ajax request :

if( click_count === max_clicks){
   console.log('Send Ajax Request');
}

NOTE: You could disable the link when you sent your request then enable it inside the ajax callback.

var click_count = 0; 
var max_clicks = 5; 
 
function call() { 
  click_count++; 
 
  console.log('Link Clicked ' + click_count + ' time(s)'); 
 
  if (click_count === max_clicks) { 
    $('#prev').addClass('disabled'); 
 
    console.log('Send Ajax Request'); 
  } 
}
.disabled { 
  pointer-events: none; 
  cursor: default; 
  color: black; 
  opacity: 0.6; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#" onclick="call()" data-tag="Prev" id="prev"> Prev </a>

Answer 2

Use this setTimeout and clearTimeout:

var ajxTimer = null;
var count = 0;
function call() {
    clearTimeout(ajxTimer);
    ajxTimer = setTimeout(function(){
        count++;
        // code your ajax here....
    },500);
}
Answer 3

you can get this like below :

var count = 0; 
 
function Previousday() { 
 
  ++count; 
  //Here ajax call 
 
  //after ajax call you can get the total count. 
 
}
<a href="#" onclick="call()" data-tag="Prev" id="prev"> Prev </a>

Answer 4

Call this function on the click event

        var click = 0; 
         
        function call() { 
          click++; 
         
          console.log('Click Count ' + click); 
        }
<a href="#" onclick="call()">Click Here</a>

Answer 5

Try this

<button onclick="myFunction()">Click me</button>

<script>
var maxClick = 10;
var clickCount =0 ;
function myFunction() {
  if(clickCount == maxClick){
  $.ajax({url: "demo_test.txt", 
  success: function(result){
   clickCount = 0;
}});
});
}else{
  clickCount++ ;
   document.getElementById("demo").innerHTML = clickCount;
}
Answer 6

Suppose you have this element:

<a href="#" onclick="call()" data-tag="Prev" id="prev"> Prev </a>

then use this js code:

var count = 0, N = 5, timeInterval = 2000, isAlreadyClicked = false, intervalObj;
function call() {
    if (isAlreadyClicked) return;
    count++;
    if (count >= N) {
        count = 0;
        clearInterval(intervalObj);
        isAlreadyClicked = true;
        // Make your AJAX call here
    }
}
intervalObj = setInterval(() => count = 0, timeInterval);

In this code, every time you click on the link, the count gets increased, but there is a time limit for that. i.e. There can't be more than e.g. 2 seconds interval between your first click and last click, otherwise the process gets restarted. So in this example, you have to click 5 times within 2 seconds in order to achieve what you're looking

If you want the user to be able to use the link only once and not ever again, you need to that isAlreadyClicked boolean to be defaultly false and when that if conditions met, you set it to true and at the first line of call function, you check that if this boolean is true, don't proceed and also use clearInterval function to clear that setInterval thing, so you don't literally waste resources.

If the user can use the link every time he clicks N times, then you don't need that boolean nor clearInterval function, just reset the count to 0.

UPDATE 1: I think I understood what you wanted to achieve after your first update. So my above JS code can change into this:

count = 0, isAlreadyInProcess = false;
function call() {
    count ++;
    if (isAlreadyInProcess) return;
    isAlreadyInProcess = true;
    setTimeout(() => {
        // make your AJAX call
        // in the SUCCESS function of that, write:
            resetData();
    }, 1000);
}
function resetData() {
    count = 0;
    isAlreadyInProcess = false;
}

You need to pay attention that I explicitly separated resetData function, because you need to call it only after your request is sent, not just on the next line!

So you have to either call this function in the success part of your JQuery AJAX call, or you have to use Promise! e.g. your call should be like this:

function ajaxCall() {
    return new Promise((resolve, reject) => {
        // make your ajax call and make sure to RESOLVE!
        // so that it goes to the chained THEN promise.
    });
}

then in the setTimeout function, write:

ajaxCall().then(res => {
    resetData();
});



=> The isAlreadyInProcess flag, makes sure that when you started to click, it doesn't call the AJAX for each click! But it waits for 1 second, courtesy of setTimout, and in this 1 second, every clicks are counted, but there won't be anymore AJAX call except the first click. After that 1 second, it makes the AJAX call, and when it's done, it resets the data and allows the user to repeat that process again, which I believe it was what you wanted.

Promisifying the AJAX calls is optional though, just to keep things solid. That depends on you whether you want to send the request and then start counting again, or ignoring that.

READ ALSO
Disable and enable multiple option tag

Disable and enable multiple option tag

I want to disable and enable my option tag value using jQueryI tried it but I didn't get solution

39
Print IFrame content generated dynamically

Print IFrame content generated dynamically

I am trying to print a HTML page in IFrame generated dynamically, with this code bellow:

35
Jquery Datatable - AJAX- No records handler

Jquery Datatable - AJAX- No records handler

I am loading data into my datatable using ajaxThis is the code:

10
How to make waypoint route from current position to db location

How to make waypoint route from current position to db location

I need to make a way point between the locatonpng to place

23