3

I want to return the second ajaxcall as result of the ajax function, can anyone help me.

private ajax(url: string, method:string, data:any = null) {
    var _this = this;
    return this.csrfWithoutDone().done(function (res) {
      $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': res
        }
      });
      return $.ajax({
        url: _this.baseUrl + url,
        type: method,
        data: data,
      });
    });
  }

the csrfWithoutDone function:

return $.ajax({
      url: _this.baseUrl + '/api/csrf',
      type: 'GET'
    });

BTW: this is writen in typescript but if you replace private with function and remove the : (type) it works in js too.

nusje2000
  • 493
  • 9
  • 25
  • 2
    I'm removing the angular2 tag since you are using jquery to make your http calls. If you think this isn't correct, please let me know. – eko Nov 25 '16 at 07:50
  • 1
    Ow yeah sure, I just added it because im using it in my project, thanks for letting me know. – nusje2000 Nov 25 '16 at 07:52
  • Maybe this is the solution to your problem: [http://stackoverflow.com/a/22063821/4217744](http://stackoverflow.com/a/22063821/4217744) – simhumileco Nov 25 '16 at 08:01
  • this code looks fine, what is the error? – Developer Nov 25 '16 at 08:10
  • Can you explain what problems your having. Is there any errors in console, from network tab in your debugger do you see anything? – Keith Nov 25 '16 at 08:21

2 Answers2

0

What you should do is CHAIN the calls.

The .done() function is asynchronous. Therefore it will execute whatever you pass it as an argument when the response is back. That function's returned value goes nowhere.

What you should do instead is: foo.then(function() { /*step 1 /}).then(function({ / step 2 */ })

I would suggest reading a little bit about asynchrounousity in Javascript.

This is the way you would do it with promises, I have never worked with jQuery so the syntax might differ.

edit: I would add that there is no way to return the response value in your initial function. the best you can do is return the jqXHR object, And then call the "then()" or "done()" from the caller.

0

You should return a Promised object in your ajax function, to be able to find out if your request is done or not. Since you are using jQuery, you can use Deferred Objects:

function ajax(url, method, data) {
    var _this = this;

    // Create a deferred object
    var dfd = $.Deferred();

    this.csrfWithoutDone().done(function (res) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': res
            }
        });

        $.ajax({
            url: _this.baseUrl + url,
            type: method,
            data: data,
        }).done(function (response) {
            // your inner ajax has been done
            // tell your promised object and pass the response to it
            dfd.resolve(response);
        });
    });

    // return promised
    return dfd.promise();
}

// call your ajax function, it is a promised object
var ajaxRequest = ajax();

// so you can wait for the response
ajaxRequest.done(function (response) {
    // your ajax has been done and you have the response
    console.log(response);
});

I've implemented a simple code to find out how Promised object works:

function ajax() {
    var dfd = $.Deferred();
    
    setTimeout(function () {
        dfd.resolve('Hello World');
    }, 1000);
    
    return dfd.promise();
}

var testResult = ajax();

testResult.done(function (response) {
    alert(response);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can use native Promise Object as well, and maybe you need polyfill, to support all browsers, see Can I Use.

dashtinejad
  • 6,193
  • 4
  • 28
  • 44