user3030089
user3030089

Reputation: 272

javascript : post data after click finished

i am trying to do post AJAX request only once after color is set for more than 2 seconds.

[DEMO FIDDLE]

fiddle

in the fiddle i want AJAX call to be fire only once after color is selected.

i don't want AJAX call to done on every click

how to do that?

Upvotes: 1

Views: 142

Answers (3)

Mx.
Mx.

Reputation: 3665

You can simply add a flag to check if your code ran before.

var timeout; 
var executed;
var arry = ['red', 'blue','orange', 'green'], i=0, len= arry.length;
    $('#element').on('click',function(){  
      $(this).css('background',arry[i++]);
        if(i===len){i=0;}
        if(!executed){
            clearTimeout(timeout);
            timeout = setTimeout(function(){     
                alert("executed");
                executed = 1;
            }, 2000);
        }
    })
#element{
    width:50px;
    height:50px;
    border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>

Demo

Upvotes: 3

D.T.
D.T.

Reputation: 350

This can be done by just adding a condition in your click event as below

 $(document).on("click", "#element", function () {
            if ($('body').data("isServerHit") === undefined) {
                $('body').data("isServerHit", true);
                setTimeout(function () {
                  // Write the code for ajax call here
                    alert('server will hit now');
                }, 2000);
            }
        });

For more details on $('body').data("isServerHit", true);, visit save data (in jquery)

Hope this helps :)

Upvotes: 0

Saksham
Saksham

Reputation: 9380

As you want it to fire only once, bind .one() instead of .on() to the element. This will make the event execute only once.

And for delay, use setTimeout().

Upvotes: 4

Related Questions