Abhik Abhik - 1 month ago 8
Ajax Question

Create a custom event upon completion of ajax call

I am trying to create a custom event listerner upon completion of a

$post
ajax call. Here is my code:

$.post( url, data, function(response) {
//Fadeout the ajax loder image
$('#ajax-image').fadeOut();

//Insert the Response (HTML Format) in a hidden div
$('#scpanels').html(response).fadeIn();

// Create an event so that other scripts can interact
$.response.trigger('MyCustomEvent');
});


And then, in other js files:

$( document ).on( 'MyCustomEvent', function() {

//Do stuffs when that AJAX call finishes

});


This is not working at all. Sorry, I am new to jQuery and this perhaps beyond my current capabilities.

Thanks

Answer

All you need to do is trigger it on the document and not on the response

like so:

$.post( url, data, function(response) {
    //Fadeout the ajax loder image
    $('#ajax-image').fadeOut();

    //Insert the Response (HTML Format) in a hidden div
    $('#scpanels').html(response).fadeIn();

    // Create an event so that other scripts can interact
    $(document).trigger('MyCustomEvent'); // only change here
});

Then it should work

Update: Simple example without ajax. I was just wondering how this works over multiple js files as I have never done that before and that is part of your question. So I just created a simple example maybe it helps you.

Create a index.html file in a directory with this content:

<!doctype html>
<html lang="en">
<head>
</head>
<body>
    <div class="click-me">click-me</div>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="./script-1.js"></script>
    <script src="./script-2.js"></script>
</body>
</html>

Then create two js files in the same directory. One script-1.js

$('.click-me').on('click', function(){
    $(document).trigger('MyCustomEvent');
});

and the other one script-2.js

$( document ).on('MyCustomEvent', function() {
    alert('it works');
});

Let me know if it works for you.