views:

43

answers:

4

Hi,

I have a php script that outputs json data. For the purposes of testing, i've put sleep(2) at the start.

I have a html page that requests that data when you click a button, and does $('.dataarea').append(data.html)

(php script returns a json encoded array. data.html has the html that i want to put at the end of <div class="dataarea">...HERE</div>.

The trouble is, if i click the button too fast (ie. more than once within two seconds (due to the sleep(2) in the php script)), it requests the php file again.

how can i make it only do one request at a time?

i've tried this (edited down to show the important parts):

amibusy=false;

$('#next').click('get_next');

function get_next() {

    if (amibusy) {
    alert('requesting already');

}
else {

    amibusy=true;
    // do the request, then do the append()
    amibusy=false;

}


}

but this doesn't seem to work. i've even tried replacing the amibusy=true|false, with set_busy(), and set_not_busy(). (and made a function am_i_busy() { return amibusy; })

but none of this seems to work. what am i missing?

A: 

Disable the button in the click event and enable it again when the request is finished. Note that the request is asynchronous (i.e. "send request" returns immediately), so you must register a function that is called when the answer comes in.

In jQuery, see the load() function and the success method plus the various AJAX events which you can tap into with ajax().

Aaron Digulla
+1  A: 

If you're in jQuery the amibusy would be jQuery.active which contains a count of currently active AJAX requests, like this:

if(jQuery.active > 0) { //or $.active
  alert('Request in Progress');
}

Keep in mind that in jQuery 1.4.3 this becomes jQuery.ajax.active.

Nick Craver
Hey, that sorted it! thanks!
phpno
@phpno - Welcome :) and welcome to SO!
Nick Craver
A: 

I'm wondering about your "do request" logic. Whenever I've done calls like this they've always been asynchronous meaning I fire the request off and then when the response comes another function handles that. In this case it would finish going through that function after setting the callback handler and set your value of amibusy back to false again before the request actually comes back. You'd need to set that variable in the handler for your post callback.

Chris
A: 

Could you use the async variable? http://api.jquery.com/jQuery.ajax/

asyncBoolean Default: true

By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

DavidYell
*Please* don't use this, it locks up the browser for no reason while the AJAX request runs, `async: true` should be avoided whenever possible.
Nick Craver
Ah! Thanks for the headsup :)
DavidYell