Search code examples
phpjavascriptjqueryajaxonkeyup

onkeyup way too slow


http://jsbin.com/ezecun/edit#javascript,html

I have to write it this way because it is dynamicly made, actual code listed below. I simplified it a bit in the jsbin. Basically it takes so long to update the array with the value of the box it is unusable.

Thanks for taking a look.

CODE: php

echo "<label style='float:left'>Comments: </label> <textarea onKeyUp=\"editItemInCart(this.value,'comments',".$itemNum.")\" onChange=\"editItemInCart(this.value,'comments',".$itemNum.")\" >".$cart['comments']."</textarea><br />";

javascript

function editItemInCart(newValue,fieldName,itemNum) {
    jQuery.ajax({
        type:"POST",
        url: "editItem.html",
        data: "newvalue=" + newValue + "&fieldname=" + fieldName + "&itemNum=" + itemNum,
    })
    //alert(newValue + fieldName + itemNum);
}

Solution

  • Do you really want to post on each typed key or when the user finishes typing? Most people can type a whole word before one letter is processed. You need a count. Something like this:

    var count = 0;
    function doEditItemInCart(newValue,fieldName,itemNum)
    {
        count++;
        setTimeout("editItemInCart('"+newValue+"','"+fieldName+"',"+itemNum+","+count+")",200);
    }
    function editItemInCart(newValue,fieldName,itemNum,cnt) {
    if (count == cnt) {
            count = 0;
            jQuery.ajax({
                type:"POST",
                url: "editItem.html",
                data: "newvalue=" + newValue + "&fieldname=" + fieldName + "&itemNum=" + itemNum,
            })
            //alert(newValue + fieldName + itemNum);
        }
    }