0
I have the code snippet below that performs a call to the method findCustomers(term, isNumber));
if(isSequenceNumber(term) && term.length >= 6){
var data = findCustomers(term, true);
console.log(data);
response(data);
}else{
var data = findCustomers(term, false);
console.log(data);
response(data);
}
The method that is not returning anything is below:
function findCustomers(term, isNumber){
$.ajax({
url: appContext + "/auth/search-customer-by-service",
type: "GET",
contentType: "application/json",
dataType: 'json',
data: {
term: term,
isNumber: isNumber
},
success: function(data) {
if (data.length > 0) {
// Com resultados de clientes.
var customerArray = new Array(data.length);
var i = 0;
data.forEach(function(entry) {
var newObject = {
label: entry.fullName + " " + "[" + entry.email + "]",
idCustomer: entry.idCustomer,
hasAvailableService: entry.hasAvailableService,
};
customerArray[i] = newObject;
i++;
});
return customerArray;
} else {
// Sem resultados de clientes.
var notFoundArray = new Array(1);
var notFoundObject = {
label: "Nenhum cliente encontrado",
idCustomer: 0,
hasAvailableService: "",
};
notFoundArray[0] = notFoundObject;
return notFoundArray;
}
}
});
}
It is worth noting that the request made by AJAX returns concrete data, but the return in the call of the function is always being undefinied
EDITED
After understanding the nature of the problem according to the answers proposed below I called the function in which performs the AJAX request via anonymity function in this way:
findCustomers(term, true, function(response){
console.log(response);
response(response);
});
But I still haven’t succeeded.
I believe it’s being returned
undefined
for the function$.ajax
is asynchronous, ie is not executed on time. In this case, the return really is nothing. What you should have was a callback withinsuccess
of your ajax where you perform the function with the results. In this case, your function$.ajax
is called and returned at the same time but the return of thesuccess
does not return to anything since it is a callback. You can try to put the parameterasync
as false. See here– Kevin Kouketsu
In fact, I was wrong in the words. It is not that it is not executed on time but rather the result you expect is not immediate.
– Kevin Kouketsu
@Kevinkouketsu, no doubt the problem is this. But unfortunately the solution of async in my case did not work.
– João Manolo
@fernandosavio, indeed the nature of the problem and the same. Thank you
– João Manolo
To create an ajax request, if/Else is inside another function?
– Chance