skip to Main Content

On a website I’m working on there is an AJAX request defined like this:

            jQuery.ajax({
            url: formURL,
            type: "POST",
            dataType: "json",
            data: postData,
            success: function (data, textStatus, jqXHR) {
                jQuery('.sib_loader').hide();
            // some more actions take place here...

That JS is in a file I can’t edit because it may be overwritten at anytime…

Can I somehow "hook" or bind my own code to that AJAX success event and and a couple of additional actions that I need to happen?

2

Answers


  1. Yes, you can "hook" into the AJAX success event without modifying the original JavaScript file. You can use the ajaxComplete event provided by jQuery, which fires when an AJAX request is completed successfully.

    Here’s an example of how you can bind your own function to the ajaxComplete event:

    jQuery(document).ajaxComplete(function(event, xhr, settings) {
        // Check if the request URL matches the URL in the original AJAX call
        if (settings.url === formURL && settings.type === "POST") {
            // Perform your additional actions here
        }
    });
    

    Make sure to include your own formURL value for the comparison. The ajaxComplete event will be triggered for all AJAX requests, so it’s important to verify that the request matches the one you’re interested in.

    Also, remember to include your custom JavaScript after jQuery has been loaded on your page.

    Login or Signup to reply.
  2. Maybe it`s too complicatedm, but I would do

        // Custom trigger using passed data
        jQuery( document.body ).on( 'your_ajax_done', afterYourAjaxDone );
        function afterYourAjaxDone(data){
            console.log(data);
        }
    
    
        function doYourAjax(){
            yourAjaxPromise(postData).then(function(data){
                // You can do stuff right here or have hook for custom trigger passing data
                jQuery( document.body ).trigger( 'your_ajax_done', data);
            });
        }
    
        // Ajax as Promise
        function yourAjaxPromise(postData) {
            return new Promise( function(resolve, reject) {
                jQuery.ajax({
                    url: formURL,
                    type: "POST",
                    dataType: "json",
                    data: postData,
                    success: function (data) {
                        resolve(data)
                    },
                    error: function (error) {
                        reject(error)
                    },
                })
            })
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search