Return True or False $.ajax(). done

Asked

Viewed 581 times

-1

Hello,

Using a change of venue ajax this way, I can return true or false.

/** ## AJAX ## **/
function getAccountAjax(id, metodo) {
    let bool;
    $.ajax({
        type: 'GET',
        async: false,
        contentType: 'application/json',
        url: 'controller/get_objeto/' + id + '/' + metodo,      
        success: (function(objeto) {        
            bool = true;
        }),
        error: (function(erro) {
            bool = false;
        })
    });
    return bool;
}

But I am using ajax, as below, however I cannot return true or false in the same way as the above example.

Can you help me ?

function getAccontAjax(id, method) {
    let bool = false;
    if (responseToken != null && responseToken != '') {
        let url = 'controller/get_account?id=' + id + '&method=' + method;
        let settings = {
            async: true,
            crossDomain: true,
            url: url,
            method: 'GET',
            headers: {
                'authorization': 'Basic YWRtaW46MTIzNA==',
                'Authorizationkeyfortoken': String(responseToken),
                'cache-control': 'no-cache',
                'postman-token': '51901e9b-3613-248b-621e-ffd06d92ded4'
            },
            processData: false,
            contentType: false,
            statusCode: {
                401: function(error) {
                    console.log(error);
                    location.href = base_url + 'token/logout';
                }
            }
        };
        $.ajax(settings).done(function(response) {
            bool = true;
        }).fail(function(e) {
            bool = false;
        });
    }
    return bool;
}

  • In the second code you are using AJAX correctly (async: true). Do not use synchronous AJAX. In the second code, when it reaches the line return bool;, AJAX has not yet received the return of the request, so bool will always be false (let bool = false;). Also, use async: true is redundant because true is already the default value of async.

  • Right, but in situation or as I might get the return as true ?

  • It depends on mt what you want to do. The right thing is to call the function and treat the return within the callback of the .done() or of .fail().

  • I am calling the ajax function, via a button, and if the return is true, I must open a modal dialog box. /** Crud **/
function create() {
 method = 'create'
 if (getAccontsAjax(0, method)) {
 showModal(method);
 }
}

  • For example: if AJAX fails and falls into .fail(), I’ll do one thing; if I fall into .done(), i do other, but every thing inside each Function.

  • Then you would put showModal(method); within the Function of the .done().

  • right, so unnecessary an if na function create() Thank you for the explanations..

  • It is not a returnable method, because in addition to waiting for a Promise, it is an encapsulated method, that is, there is no possibility of externalizing it, but you can pass the data at the end of the Promise through a callback method.

Show 3 more comments

2 answers

1

Simply change the async setting from true to false, as follows:

function getAccontAjax(id, method) {
    let bool = false;
    if (responseToken != null && responseToken != '') {
        let url = 'controller/get_account?id=' + id + '&method=' + method;
        let settings = {
            async: false,
            crossDomain: true,
            url: url,
            method: 'GET',
            headers: {
                'authorization': 'Basic YWRtaW46MTIzNA==',
                'Authorizationkeyfortoken': String(responseToken),
                'cache-control': 'no-cache',
                'postman-token': '51901e9b-3613-248b-621e-ffd06d92ded4'
            },
            processData: false,
            contentType: false,
            statusCode: {
                401: function(error) {
                    console.log(error);
                    location.href = base_url + 'token/logout';
                }
            }
        };
        $.ajax(settings).done(function(response) {
            bool = true;
        }).fail(function(e) {
            bool = false;
        });
    }
    return bool;
}

1


The method $.ajax({...}) is not returnable, because in addition to expecting a Promise, it is an encapsulated method, that is, there is no possibility of externalizing it, but vc can pass the data at the end of the Promise through a callback method, or through a branch of Promises:

With natural callback:

function getAccountAjax(id, callback) {
    $.ajax({
        type: 'GET',
        async: false,
        contentType: 'application/json',
        url: 'controller/get_objeto/' + id + '/' + metodo,      
        success: (function(objeto) {        
            callback(objeto, false);
        }),
        error: (function(erro) {
           callback(erro, true);
        })
    });
}

getAccountAjax('1', function(result, error) {
   if (result.status == true && error === false) {
      //aqui retorna o true ou dados que vem da api
   }
  if (!result.status && error === false) {
      //erro interno na api
   }
  if (error === true) {
     //erro do evento ajax
     console.log(result)
   }
});

With Promise:

function ajax(options) {
  return new Promise(function (resolve, reject) {
    $.ajax(options).done(resolve).fail(reject);
  });
}

ajax({
  url: someURL,
  type: 'post',
  contentType: 'application/json; charset=utf-8',
  data: JSON.stringify({
    something: something,
    anotherthing: anotherthing
  })
}).then(
  function fulfillHandler(data) {
    // ...
  },
  function rejectHandler(jqXHR, textStatus, errorThrown) {
    // ...
  }
).catch(function errorHandler(error) {
  // ...
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.