Ajax after does not work bind event

I using Jquery with ajax. I doing after click,unbind and after ajax bind click. but Bind method not working. Please help me

$(".lang").on("click", function (e) {

    $(this).unbind('click');

    if ($(this).hasClass("disabledLanguage")) {

        return false;
    }
    var token = $('[name=__RequestVerificationToken]').val();

    $.ajax({
        type: "POST",
        url: Host + "Language",
        data: { __RequestVerificationToken: token, Code: $(this).data("code") },
        success: function (data) {

            if (data.IsCompleted) {

                //window.location = window.location.href;
            }
            else {
                //alert("Error");
            }

            $(this).unbind('click'); //<----Notworking
        }
    });
      return false;

    });

Answers 1

  • /**
     * make a function to handle the click event stand alone
     * it's good for reuse and test
     */
    function clickHandler(e){
        /**
         * cache the result of $(this)
         * for performance and reuse in another function context
         */
        var $lang = $(this);
    
        $lang.unbind('click', clickHandler);
    
        if ($lang.hasClass("disabledLanguage")) {
            return false;
        }
    
        var token = $('[name=__RequestVerificationToken]').val();
    
        $.ajax({
            type: "POST",
            url: Host + "Language",
            data: { __RequestVerificationToken: token, Code: $lang.data("code") },
            success: function(data) {
    
                if (data.IsCompleted) {
    
                    //window.location = window.location.href;
                } else {
                    //alert("Error");
                }
    
                /**
                 * doing after click,unbind and after ajax bind click
                 * so it should be bind click but not unbind click
                 */
                $lang.bind('click', clickHandler);
            }
        });
        return false;
    }
    
    $(".lang").on("click", clickHandler);
    

    May be this can help you, and more detail in the comments


Related Articles