javascriptjqueryhtmlajax

Click a button using jQuery and append data to response after ajax success


I have two buttons and one of them is already bound with an ajax call from a different site. I need to call the ajax using the first button and also I need to append some data to the result after ajax completion.

(Unfortunately, I have no access to edit the ajax function or existing jQuery. All I can do is that create a new function).

Simply I need to call this from the console. Is there any jQuery function to know whether an ajax is called and that one has a success response?

I tried to use ajaxStart() and ajaxStop(), but not working.

This what I tried:

jQuery('.a').click(function(){
  var valuetopass;
  //Copy Value from input of A
  jQuery(document).ajaxStart(function(){
    console.log('Click Ajax Button');
    valuetopass = jQuery('.a_value').val();
  });

  //Call Ajax
  jQuery('.b').click();

  //Paste Value to the result appended
  jQuery(document).ajaxStop(function(){
    console.log('Appended the result input field(b_value) to the html.');
    
    //Paste the value in new field from ajax.
    jQuery('.b_value').val(valuetopass);
  });
});
<input class="a_value" value="ABC"/>
<button class="a">Button to initiate ajax</button>
<button class="b">Button having Ajax</button>

Here when we click on button A it will initiate a click on button B and ajax will call. After that, the result will append an input field in HTML like <input class="b_value"/> . I need to add value to this field using an external jQuery function.

I have also tried

setTimeout(function(){
  jQuery('.b_value').val(valuetopass)
},500);

But we can't say 500 ms will be the exact time taken. Is there any possibility to find the ajax called and finished?


Solution

  • You can use .ajaxComplete(), use it like this

    $( document ).ajaxComplete(function(event, xhr, settings) {
      console.log(xhr.responseText);
    });
    

    Here xhr.responseText will be having the response of every ajax call made by jQuery ajax method. So your response <input class="b_value"/> can be processed inside this callback