Debopam Parua
Debopam Parua

Reputation: 530

Detecting end of ajax call from an external function

I am working in a project that has created plugins in JavaScript for making some ajax calls. I am not allowed to change the code in the plugins.

There is a button class in the plugin, which when clicked performs an ajax and changes a field in the database and changes the text color of the clicked button based on the boolean value returned. There is a dynamic list of similar buttons (number of buttons is not fixed) and each when clicked makes changes to the database in the same way and gets assigned a state based on the boolean returned.

Now, when any of these buttons is clicked, I need to check the number of buttons in each state and output the result to the console.

I am detecting the button click with $(document).on('click', 'button.plugin-button', function() {}) but, it is not giving me correct results, as the ajax is being executed from inside the plugin code and my button click handler is being executed before the ajax.

Is there any way I can detect the execution of the AJAX and when it is completed, call my click handler and display the correct result?

Upvotes: 0

Views: 803

Answers (1)

B. Waqar
B. Waqar

Reputation: 76

You can use ajaxComplete

$( document ).ajaxComplete(function( event, xhr, settings ) {
if ( settings.url === "ajax/test.html" ) {
    $( ".log" ).text( "Triggered ajaxComplete handler. The result is " +
  xhr.responseText);
}});

or callback function like

function checkButtonsState(){}
function makeAjaxRequest(para1, para2, callback){
/*onsuccess or on error complete*/
callback();
}
/*call it like*/
makeAjaxRequest("para1","para2", checkButtonsState)

Upvotes: 5

Related Questions