Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click - prevent multiple clicks in mobile

I'm using Phonegap for building my iOS/Android app - basically a remote that can emulate a few keys on my laptop's keyboard. (To control video playback etc).

Since its a webpage, I have images that when clicked connects to my Java Socket server on my laptop. The issue I'm facing is, everytime I click a button - just once (like the pause button), I see more than 1 request being fired in the java console. But this happens only when I click (touch) in my phone. When I try the same in my laptop's browser, it behaves as expected (just one request).

I went through several posts, where the general advise is to use 'unbind()' and 'off()', but nothing seems to work. The code snippet is below.

$("#play").off().on('click',function(){
        //alert("Play");

    jQuery.ajax({
    type: "GET",
    async: true,
    url: 'http://'+ip+':10007/function=play?',
    success: function (msg) 
        {  },
    error: function (err)
        { }
    });
});

I used that alert to check if the event gets fired more than once. The alert pops up just once, which means, the event is fired just once. So its just once click (touch) => One event => But multiple requests!

I'm checking the server response with this piece of code:

while(true) {                
      Socket sock = servsock.accept();                
      System.out.println("Connection from: " + sock.getInetAddress());                
      Scanner in = new Scanner(sock.getInputStream());                
      PrintWriter out = new PrintWriter(sock.getOutputStream());                
      String request = "";                
      while (in.hasNext()) {
          request = in.next( );                
          if (request.contains("function="))
          {
            inputLine = request.split("function=")[1];
            System.out.println ("^^^^^" + inputLine); 
            ...

The output appears thrice in the console when requested from mobile, but just once when request from my laptop's browser.

I don't understand why and not sure how it can be prevented. Any pointers?

like image 489
Krish Avatar asked Oct 09 '16 02:10

Krish


1 Answers

Another way you can resolve this problem is using a flag that you can set once you click the button. You can then check the value of the flag and return false; in case the value is already set.

// Pseudo Code
- Keep the flag to false initially.
- On Click, check the flag value.
-- If the flag is set, return false;
-- If the flag is not set, set the flag.
- Once the success method is called, reset the value to false again.

This will resolve the issue of multiple calls at least. Another exercise would be to determine why this is an issue only on a device.

like image 91
Jonathan Cardoz Avatar answered Oct 06 '22 09:10

Jonathan Cardoz