-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 linereturn bool;
, AJAX has not yet received the return of the request, so bool will always be false (let bool = false;
). Also, useasync: true
is redundant becausetrue
is already the default value ofasync
.– Sam
Right, but in situation or as I might get the return as true ?
– Wagner Fillio
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()
.– Sam
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);
 }
}
– Wagner Fillio
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.– Sam
Then you would put
showModal(method);
within the Function of the.done()
.– Sam
right, so unnecessary an if na
function create()
Thank you for the explanations..– Wagner Fillio
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.
– Ivan Ferrer