Reputation: 3129
I have an ajax call that is of type post and I want to return the data by way of using return.
I have tried:
function GetDataById(Id){
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify({ ID: Id }),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
return data;
},
error: function (jqXHR, exception) {
}
});
}
and I have tried:
function GetDataById(Id){
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ ID: Id }),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
return data;
},
error: function (jqXHR, exception) {
}
});
}
and what I am doing is:
(function(){
const data = GetDataById(208);
console.log(data);
})();
Upvotes: 0
Views: 29
Reputation: 743
$.ajax()
returns a promise. If you want to implement a function that gets the data after the call, you can simply return $.ajax()
call and use promise's then and catch instead.
function GetDataById(Id){
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify({ ID: Id }),
contentType: "application/json; charset=utf-8"
});
}
(function(){
GetDataById(208).then(data => console.log(data));
})();
Upvotes: 1