This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I've built a function to handle a request that I intend to use in various pages. But I can't find a way to access it's return! Here is what my code looks like:
function buscaIdEmpresa() {
var jsonEmail = { "email": emailCurrentUser };
var jsonEmailString = JSON.stringify(jsonEmail);
var test = $.ajax({
url: "https://localhost:44326/test",
type: "post",
async: false,
crossDomain: true,
data: jsonEmailString,
contentType: "application/json",
dataType: "json",
complete: function (data) {
var id = data.responseText;
alert(id)
//this returns id as expected
return id;
}
});
alert(test)
//this returns object Object
return test;
}
function carregaConfigList() {
var id = buscaIdEmpresa()
alert(id)
//this returns object Object
}
Also I am not entirely sure that this is the correct way to tackle the problem. I'm open to suggestions, but I would not like to write the entire ajax function every single time the request needs to be done. How can I access the object value? Is there a more 'correct' way of doing this?
Couple ways you could do this, my preferred method is using async/ await
function buscaIdEmpresa() {
return new Promise(resolve => {
var jsonEmail = { "email": emailCurrentUser };
var jsonEmailString = JSON.stringify(jsonEmail);
$.ajax({
url: "https://localhost:44326/test",
type: "post",
async: false,
crossDomain: true,
data: jsonEmailString,
contentType: "application/json",
dataType: "json",
complete: function (data) {
var id = data.responseText;
resolve(id);
}
});
})
}
async function carregaConfigList() {
var id = await buscaIdEmpresa()
alert(id)
}
But you could also use a callback pattern
function buscaIdEmpresa(callback) {
var jsonEmail = { "email": emailCurrentUser };
var jsonEmailString = JSON.stringify(jsonEmail);
$.ajax({
url: "https://localhost:44326/test",
type: "post",
async: false,
crossDomain: true,
data: jsonEmailString,
contentType: "application/json",
dataType: "json",
complete: function (data) {
var id = data.responseText;
callback(id);
}
});
}
function carregaConfigList() {
buscaIdEmpresa(function(id){
alert(id)
})
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
function getData(url) {
var responseData = null;
$.ajax({
type: "GET",
url: url,
crossDomain: true,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (result) {
responseData = result;
}
});
console.log(responseData);
return responseData;
}
var getapidata= getData('https://jsonplaceholder.typicode.com/todos/1');
console.log('getapidata',getapidata);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
It's an async event, So you should do something similar this syntaxe may help:
function getData(url) {
return $.ajax({
type: "GET",
url: url,
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "jsonp"
});
}
var getapidata = getData('https://jsonplaceholder.typicode.com/todos/1').then(value => {
console.log(value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I think you don't want to write $.ajax syntax every time when you need to send ajax call. if so then this code can help you.
Note You should must learn how JavaScript asynchronously works because the which you have written will never work.
Here is my code in which i have add some more functionality.
1) dynamically set URL and Methods
2) Now you can GET, POST, PUT, PATCH, DELETE using getData() function
getData() function required two parameter and one optional parameter depending upon you need to send data on server or not.
getData(URL, Method, Data if there)
$(document).ready(async () => {
function getData(url, method, data = {}) {
return $.ajax({
method,
url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
});
}
// getData(URL, Method, Data)
// await getData('https://jsonplaceholder.typicode.com/posts/1', 'PATCH', {title: "new post"})
// await getData('https://jsonplaceholder.typicode.com/posts/1', 'DELETE')
// await getData('https://jsonplaceholder.typicode.com/posts', 'POST', {
// userId: Math.floor(Math.random() * 1000),
// title: "New Post",
// body: "This is my new post"
// })
var getapidata = await getData('https://jsonplaceholder.typicode.com/posts/1', 'GET')
console.log(getapidata)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Thank you
I am looking to store a value which is return by the AJAX function, here is the my code, in the AJAX success it is showing well, but when am storing that data which is saying undefined.
The following serviceNumber, which I am storing the enCrypt return value
var serviceNumber = enCrypt(typeofServiceNumber);// when am catching the function data which is saying "undefined"
the following code is my ajax function
function enCrypt(id) {
if (id > 0) {
$.ajax({
url: $("baseUrl").html() + "JobProfiles/Encryption",
type: "POST",
dataType: "json",
data: { Id: id },
success: function (encdata) {
return encdata;
},
error: function (data) {
$('#loading').hide();
}
});
}
}
Can you help me to know what is wrong in my code? Thanks in advance.
You can't use return like this, because the function is async + it's a function in a function...so actually yeah you cant return there xD
Just do something like:
enCrypt(typeofServiceNumber);
//and in your ajax:
success: function (encdata) {
go_on(encdata);
},
//and then
function go_on(serviceNumber)
{
//here you can use it :D
}
just add the
cache: false,
async: false,
to you ajax function
function enCrypt(id) {
var encnum;
$.ajax({
url: $("baseUrl").html() + "JobProfiles/EncodeIds",
type: "POST",
cache: false,
async: false,
dataType: "Json",
data: { Ids: id },
success: function (encdata) {
encnum = encdata;
},
error: function (data) {
$('#loading').hide();
}
});
return encnum;
}
The alert at the start shows "undefined", why?
The alerts come in this order:
"success!"
"Data" (what it should be)
"undefined"
I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!
Very grateful for any help!
I got this code
var data = getData("");
alert(data); <<<<<<< UNDEFINED
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
function processData(data) {
var arrData = CSVToArray(data);
dimensions = arrData[0];
var objects = [];
objects[0] = dimensions;
for (var i = 1; i < arrData.length; i++){
objects[i] = new Object();
for (var j = 0; j < dimensions.length; j++){
objects[i][dimensions[j]] = arrData[i][j];
}
}
return objects;
}
To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.
Your getData function doesn't return anything.
You need to return it from the function itself.
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
^ This returns the data within getData. But getData doesn't do anything with it: such as returning it.
function getData(fileName) {
var ourData = "";
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
ourData = arrData;
},
});
return ourData;
}
This returns the data from getData to whatever calls that function.
edit: also, don't use async:false. Your browser won't capture any events happening until that AJAX completes. The benefit of asynchronous JS is that...we can! And in this case should.
Preface: Don't use async: false. But answering the question:
getData doesn't return anything. You're doing a return from the success callback, but that returns something from the success callback, not getData.
To change it so getData returns something, you'd do this:
function getData(fileName) {
var arrData;
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
arrData = processData(data);
},
});
return arrData; // <=== Now `getData` returns something
}
But don't do that. Instead, embrace asynchronous programming and remove async: false. For instance, a callback:
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
});
}
...called like this:
getData(function(data) {
alert(data);
});
...or a promise ($.ajax returns one, of sorts):
function getData(fileName) {
return $.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
}).then(data) {
return processData(data); // <== Becomes the resolution value of `getData`'s promise
});
}
and then
getData().then(function(data) {
alert(data);
});
data is undefined because the function getData doesn't return anything. You should have a look at promises.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a ajax call inside a function that returns a json object on success function, i need to set returned data to a variable, searched for answer but i couldn't find any useful answers.
Method 1:
im calling a function and setting returned value to a variable like this
var obj = ajaxCall();
my code is like
function ajaxCall(){
var result;
$.ajax({
url: url_of_my_php_file,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function(data) {
// it returns json Object "data"
result = data;
}
});
return result;
}
if i log the data inside success callback my json is similar to this
[{ collection: "Super Hero", img:"http://img_url.jpg",
heros: [{ id: "111", text: "Iron Man" },
{ id: "123", text: "Superman" },
{ id: "124", text: "Batman" }]
}]
but it is not returning value, instead of value it returns empty string, because that return function doesn't wait for ajax success function.
Method 2:
I have tried with calling function from success and returning value from that funcion, like this
function ajaxCall(){
var result;
$.ajax({
url: url_of_my_php_file,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function(data) {
// it returns json Object "data"
callBack(data);
}
});
function callBack(data){
return data;
}
return callBack();
}
in this case the function is returning the value but only another array inside main array (heros) only, not outside variables, how to fix it?
i tried above methods, and i have seen something like below (not sure where i have seen this) to set ajax result directly to variable
function ajaxCall(){
var result= $.ajax({
url: url_of_my_php_file,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function(data) {
// it returns json Object "data"
result = data;
}
},(0);
}
is this method is valid?
if not, then is there any way to get that string to result variable and return it to obj?
Update:
I have tried this link, but that method is not working for me, if it is not working for me then how it is a copy?
Use callbacks
function ajaxCall(callback){
$.ajax({
url: url_of_my_php_file,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: callback
});
}
ajaxCall(result => {
//do something with result
})
Or Promises
function ajaxCall(callback){
return new Promise((resolve, reject) => {
$.ajax({
url: url_of_my_php_file,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: resolve,
error: reject
});
});
}
ajaxCall()
.then(result => {
//do something with result
})
.catch(err => {
//or err
});
Try this
var obj;
$.ajax({
url: url_of_my_php_file,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function(data) {
// it returns json Object "data"
obj = data;
}
});
I have this code:
my.data = function () {
var getAuth = function (userName, password) {
var model = JSON.stringify({ "UserName": userName, "Password": password });
var result;
$.ajax({
url: my.baseUrl + "api/AD",
type: "POST",
data: model,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
result = data;
return result;
}
});
}
return {
getAuth: getAuth
}
}();
when I call getAuth , i can see data returns "true" but the the calling function -
var result = my.data.getAuth(username,password); returns undefined.
any idea?
Sure, it will return undefined, the returned value is of the success function. Not the value of the getAuth function. You should change to:
my.data = function () {
var getAuth = function (userName, password) {
var model = JSON.stringify({ "UserName": userName, "Password": password });
var result;
$.ajax({
url: my.baseUrl + "api/AD",
type: "POST",
data: model,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
result = data;
}
});
return result;
}
return {
getAuth: getAuth
}
}();
Even though this solution works, the use of async: false is not recommended.
Two reasons:
1. When you switch ajax to async: false, you shouldn't pass success: function(){...} property to options hash. Instead of this you should to use chain.
2. When you use return in success function you return from success function only, not from getAuth.
Try this:
$.ajax({
url: my.baseUrl + "api/AD",
type: "POST",
data: model,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
}).success: function (data) {
result = data;
};
return result;
And couple of notes. As you know switching to async: false can cause long delay. This is bad practice and it is deprecated in last JQuery versions. Instead of this you should to use callbacks. Third argument of your getAuth method can be a function, that you should run when query is success:
var getAuth = function( userName, password, callback ){
$.ajax({
url: my.baseUrl + "api/AD",
type: "POST",
data: {userName: userName, password: password},
success: function (data) {
callback( data );
}
});
}
And use this like here:
my.data.getAuth( 'someusername', 'somepassword', function( data ){
alert( 'It looks like your authorized successfully' );
});