Search code examples
jqueryajaxjquery-callback

How to execute jQuery callback before data?


I have a simple post, which executed the data returned as a script as such:

$.post("/home", { foo: 'bar' }, function(){
    //callback function
}, "script");

Here's what happens:

  1. The request gets sent
  2. A piece of JS code is returned as a response and executed
  3. The callback is executed

I need the callback to be executed before the returned JS is executed. Is there a way to achieve this?

Thanks!


Solution

  • You can't change how jQuery handle the request. After all, a callback is a callback and it gets executed once the job is done! You can, however, set the dataType to "text" and then eval your Javascript.

    Ex:

    $.post("/home", { foo: 'bar' }, function(data){
       //callback function
    
       // execute JS
       $.globalEval( data );
    }, "text");
    

    ** UPDATE **

    This is what jQuery does internally (snipped) :

    // If the type is "script", eval it in global context
    } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
       jQuery.globalEval( data );
    }
    

    So, there is no security risk with taking the globalEval out of the Ajax request and executing it in the callback function.