Search code examples
jqueryjquery-validateunobtrusive-ajax

jquery.unobtrusive-ajax plugin broken when updating to Jquery 1.9.0


Possible Duplicate:
jQuery 1.7 - Turning live() into on()

//Solution: I simply replaced the four occurrences like the approved answer suggested and unobtrusive ajax plugin is up and working again with jquery 1.9.0

Update//Observe the comments for the answer marked at the bottom which is the best way to solve this.

//Original post: I upgraded to jQuery 1.9.0 but then unobtrusive ajax plugin went down since they deprecated the live method. I tried to replace it like this since the upgrade fixes an other bug for me. However, it does not work. I simply replaced live with on like this:

$("a[data-ajax=true]").on("click", function (evt) {
        evt.preventDefault();
        asyncRequest(this, {
            url: this.href,
            type: "GET",
            data: []
        });
    });

    $("form[data-ajax=true] input[type=image]").on("click", function (evt) {
        var name = evt.target.name,
            $target = $(evt.target),
            form = $target.parents("form")[0],
            offset = $target.offset();

        $(form).data(data_click, [
            { name: name + ".x", value: Math.round(evt.pageX - offset.left) },
            { name: name + ".y", value: Math.round(evt.pageY - offset.top) }
        ]);

        setTimeout(function () {
            $(form).removeData(data_click);
        }, 0);
    });

    $("form[data-ajax=true] :submit").on("click", function (evt) {
        var name = evt.target.name,
            form = $(evt.target).parents("form")[0];

        $(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);

        setTimeout(function () {
            $(form).removeData(data_click);
        }, 0);
    });

    $("form[data-ajax=true]").on("submit", function (evt) {
        var clickInfo = $(this).data(data_click) || [];
        evt.preventDefault();
        if (!validate(this)) {
            return;
        }
        asyncRequest(this, {
            url: this.action,
            type: this.method || "GET",
            data: clickInfo.concat($(this).serializeArray())
        });
    });

Solution

  • Equivalent of live using on (delegation) is:

    $(document).on("click","a[data-ajax=true]", function (evt) {...});
    

    You can find jquery's .on() method documentation here:

    >> http://api.jquery.com/on/ <<

    The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live().

    To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()