www.webdeveloper.com
Results 1 to 2 of 2

Thread: Preventing on click event until after database is updated from prior click

Hybrid View

  1. #1
    Join Date
    Apr 2012
    Posts
    12

    Preventing on click event until after database is updated from prior click

    Hello,
    I have a div contained in an object that registers for a click event, and once clicked, uses ajax to communicate with the server and update a user rating for an item.

    When updating the rating, it checks if the item already exists in the database, if not, I use an INSERT, otherwise I use an UPDATE. My issue is that if the user clicks very quickly, two INSERTS are run and i end up with duplicates in my database. Is there a standard means of preventing this or disabling the onclick and re-enabling it on the ajax call back?

    Here is my abbreviated code:

    PHP Code:
    $sql="UPDATE database SET rating=" $_POST['rating'] . ", status=" $_POST['status'] . " WHERE user=" $_POST['user'] . " AND isbn=" $_POST['isbn'];

        
    $result mysql_query($sql);       
        if (
    mysql_affected_rows()==0) {
            
    $sql="INSERT INTO database (user, isbn, rating, status) VALUES (" $_POST['user'] . ", " $_POST['isbn'] . ", " $_POST['rating'] . ", " $_POST['status'] . ")";
                if (!
    mysql_query($sql$connection))
            {
                echo(
    "------Book failed to add------");
            }
            else
            {
                echo(
    "------Book successfully added------");
            }
        }
        else
        {
            echo(
    "------Book successfully updated------");
        } 
    Code:
    //add event listener
    star1.addEventListener('click', function(e){changeYouStars(e, mySelf);}, false);

  2. #2
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    You could either remove the event listener when clicking the button and add it again when the request is done, or just set a boolean that keeps track if a request is in progress or not - something like this:
    Code:
    var isRequesting = false;
    
    star1.addEventListener('click', function(e){
        if (!isRequesting) {
            isRequesting = true;
            changeYouStars(e, mySelf);
        }
    }, false);
    
    function onRequestComplete() {
        isRequesting = false;
    }

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles