10

I want to execute a piece of javascript after the ajax response has been rendered. The javascript function is being generated dynamically during the ajax request, and is in the ajax response. 'complete' and 'success' events to not do the job. I inspected the ajax request in Firebug console and response hasn't been rendered when the complete callback executes.

Does not work:

      function reloadForm() {
        jQuery.ajax({
          url: "<generate_form_url>",
          type: "GET",
          complete: custom_function_with_js_in_response()
        });
      };

ajaxComplete does the job, but it executes for all the ajax calls on the page. I want to avoid that. Is there a possible solution?

$('#link_form').ajaxComplete(function() {
  custom_function_with_js_in_response();
});
4
  • Why not use ajaxComplete? It may execute for every ajax calls but using a condition in it would fix the errors that may occur on "normal" requests. Or you could use a wrapper for such ajax calls that define the ajaxComplete method and inside it it removes itself once it is called... Commented Sep 24, 2012 at 9:57
  • 1
    Please put the code. Ideally if you are putting code in success/error method of ajax, it should work. However if code is present, we can figure out if you are doing any mistake. Commented Sep 24, 2012 at 9:57
  • what JS framework do you use? Can yu put the code sample? Commented Sep 24, 2012 at 9:58
  • @Salketer...didn't get the second part of your comment. Can you please elaborate. Added code, and I use jquery. Commented Sep 24, 2012 at 10:18

4 Answers 4

14

you can also use $.ajax(..).done( do_things_here() );

$(document).ready(function() {

    $('#obj').click(function() {

    $.ajax({
        url: "<url>"
    }).done(function() {
      do_something_here();
    });
});

});

or is there another way

$(document).ready(function() {

    $('#obj').click(function() {

    $.ajax({
        url: "<url>",
        success: function(data){
          do_something_with(data);
        }
    })
});

});

Please, utilize this engine for share your problem and try solutions. Its very efficient.

http://jsfiddle.net/qTDAv/7/ (PS: this contains a sample to try)

Hope to help

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the done callback was what I needed. I have used $.ajax().always() instead.
1

Checking (and deferring call if needed) and executing the existence of the callback function might work:

// undefine the function before the AJAX call
// replace myFunc with the name of the function to be executed on complete()
myFunc = null; 

$.ajax({
    ...
    complete: function() {
       runCompleteCallback(myFunc);
    },
    ...
});

function runCompleteCallback(_func) {
    if(typeof _func == 'function') {
        return _func();
    }
    setTimeout(function() {
        runCompleteCallback(_func);
    }, 100);
}

4 Comments

Awesome! This works. Would you mind explaining the runCompleteCallback function that defers the call. Will it keep on retrying multiple times after 100ms, until the function is executed, or will it just try once?
The runCompleteCallback function checks if the passed in function exists (which mean the AJAX response has already gone into the DOM) and executes it if it does. If it doesn't, it tries again after 100ms (change this duration as needed). In most cases, it will pass in the second run max (unless data-insertion into the DOM takes a long time, which is unlikely).
But I already have that function in DOM on initial load, and reload it via the ajax call (The js function is generated dynamically). So it will always find the function there. Will it execute the older version of the function if the ajax call isn't completed in the timeout duration, or my understanding is incorrect?
Oh.. In that case you'll need some mechanism to ensure that the correct (latest) version of the function is being executed. You can do that by redefining the function to null ( myFunc = null; ) immediately before the AJAX call, so that runCompleteCallback thinks it does not exist and will wait till the new version gets pushed into the DOM.
0

Can't help a lot without code. As an general example from JQuery ajax complete page

$('.log').ajaxComplete(function(e, xhr, settings) {
    if (settings.url == 'ajax/test.html') {
        $(this).text('Triggered ajaxComplete handler. The result is ' +
                 xhr.responseHTML);
    }
});

In ajaxComplete, you can put decisions to filter the URL for which you want to write code.

1 Comment

I wouldn't prefer adding if condition based on the ajax request path because the routes may change, and the code will fail without anyone noticing. Additionally, I request the same url with GET, POST and PUT requests. Is there an alternative way of doing it?
0

Try to specify function name without () in ajax options:

function reloadForm() {
        jQuery.ajax({
          url: "<generate_form_url>",
          type: "GET",
          complete: custom_function_with_js_in_response
        });
      };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.