Question

I'd like to hook into a ajax callback for a specific form that's using unobtrusive ajax. The ajax call is no problem with this standard form using unobtrusive ajax:

<form action="/xyz" data-ajax="true" data-ajax-method="POST" id="someformid" method="post">
    <input type="text" name="bla" />
    <button>submit</button>
</form>

My first approach was this:

var form = $("#someformid");
$(document).ajaxComplete(function (e, request, options) {
    // is not hitting here
});

But that doesn't seem to work. This approach hits the handler, but not just for the desired form. But for all ajaxComplete events.

var form = $("#someformid");
form.submit(function (eevent) {
    $(document).ajaxComplete(function (e, request, options) {
        // this hits ok. but not just for this form
    });
});

Next option would be to use the "data-ajax-success". but that doesn't seem to supply the form context.

So the question: How do I hook up a ajaxComplete event for just one form exclusively.

Note: I'd like to avoid workarounds like matching the url or adding some unique id to the query.

Thanks!

Was it helpful?

Solution

From the .ajaxComplete() docs:

As of jQuery 1.8, the .ajaxComplete() method should only be attached to document. All ajaxComplete handlers are invoked, regardless of what Ajax request was completed. If you must differentiate between the requests, use the parameters passed to the handler. Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, you can restrict the callback to only handling events dealing with a particular URL:

So, the way I read this is, if you know you'll be running a specific URL (your php processing script), then you can pass that URL in the settings to the .ajaxComplete() method.... (in your case, "/xyz")

$( document ).ajaxComplete(function( event, xhr, settings ) {
  if ( settings.url === "/xyz" ) {
    $( ".log" ).text( "Triggered ajaxComplete handler. The result is " +
      xhr.responseHTML );
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top