0

I'm sending HTTP requests with jQuery's AJAX and it doesn't return a value.

I created a Http object that handles the request and a request() method that is supposed to return the gotten from the request.

 class Http
  constructor(url,type = 'GET') {
      this.url = url,
      this.type = type;
  }
  request() {
       let response = ''; 
        $.ajax({ 
              'url': this.url, 
              'type': this.type,
              dataType: 'json',
              success: (data) => {
                   response = data
                    // console.log(data) - **works**
                    // return data - **doesn't work**
              },
              error: (error) => {
                    response = data;
              }
        });     
      return response;}   
Maverick
  • 962
  • 9
  • 12
  • 1
    This is almost certainly something to do with asynchronous behaviour https://stackoverflow.com/questions/6685249/jquery-performing-synchronous-ajax-requests – sanjsanj May 13 '19 at 16:55

1 Answers1

0

An AJAX request is by nature asynchronous, therefore, you don't know when it will be completed. To solve this problem, a callback function is used. This callback is called when the request is complete. (There are one callback for success and one for error).

http.request(...);
// Here, the ajax request is not completed yet.

You can't return the result of the call synchronously so you have to use it inside your callback function.

$.ajax({ 
      'url': this.url, 
      'type': this.type,
      dataType: 'json',
      success: (data) => {
          // use the response here only
      },
      error: (error) => {
          // Handle errors here
      }
});

If you return inside your callback, the return is for the callback function, not the enclosing one.


You can but you SHOULDN'T make your ajax call synchronously. Add a parameter to your ajax call:

$.ajax({ 
      'url': this.url, 
      'type': this.type,
      dataType: 'json',
      async: false, // Add this
      success: (data) => {
          // use the response here only
      },
      error: (error) => {
          // Handle errors here
      }
});

This way IS NOT recommended since it will freeze your application until you get a response.

SystemGlitch
  • 2,150
  • 12
  • 27
  • I know, just trying to keep the code minimal for Stackoverflow. That's why I removed it, Thanks by the way. – Maverick May 13 '19 at 16:58
  • @Maverick I updated my answer to emphasize on the callback function being returned instead of the enclosing one. – SystemGlitch May 13 '19 at 17:01