Last week I had an interesting challenge come up in regard to AJAX. I wrote an .ajax call so javascript submit data in lieu of using a form that existed. I grabbed the form’s action attribute to use as the URL and sent the data.

$.ajax({
    url: $('#submit-form').attr('action'),
    data: { name: 'generic' }
});

The problem was that there was a response from the controller of JSON data that needed to be processed. Elsewhere the form already had a function that triggered on ajax:success.

$('#submit-form').bind('ajax:success', function(e, response){
    // do stuff
});

But because the form wasn’t directly sending the new .ajax call it wasn’t receiving the response to trigger the bound function. The challenge was that the form was still being used and couldn’t be touched, and obviously I didn’t want to replicate the code in my ajax call. I thought about removing the code to a helper function and calling it from both places.

But then I found my answer: I can manually trigger that bound function from elsewhere in the code.

$.ajax({
    url: $('#submit-form').attr('action'),
    data: { name: 'generic' },
    success: (event, success) => {
        $('#submit-form').trigger('ajax:success', event);
    }
});

Nice and simple and I never had to touch the original code!