Commonly, ajax method is executed asynchronously, and some operation against the result is done in the done method.
In this article, I am going to describe about how to save ajax result into a variable instead of processing in the done method.
Common usage of ajax
Commonly, ajax is used as below.
In this way, we have to write the continuation in the done method.
const url = 'http://fuga.com'
$.ajax({
type : 'get',
url : url,
}).done(function(response){
//operation against response
.
.
.
}).fail(function(error){
console.log(error)
})
Trying to save ajax result into a global variable
When you try to save ajax result into a global variable, you may come up with such as below code.
But it dose not work.
undefined would come in the result valiable.
const url = 'http://fuga.com'
let result
$.ajax({
type : 'get',
url : url,
}).done(function(response){
result = response
}).fail(function(error){
console.log(error)
})
console.log(result) //undefined
Correct way to save ajax result into a global variable
Ajax has async option. When you set false on async option, ajax would be executed synchronously and would be able to save the result into a global variable.
All we have to do is add async : false as below.
const url = 'http://fuga.com'
let result
$.ajax({
type : 'get',
url : url,
async : false, //add
}).done(function(response){
result = response
}).fail(function(error){
console.log(error)
})
console.log(result) //ajax result
Getting together ajax process as a function.
We can get together ajax process as a function, and then it would be more useful.
Procedural processing code has become crear.
const url = 'http://fuga.com'
response = getAjax(url, {'id':1})
function getAjax(url, data=null) {
let result = null
$.ajax({
type : 'get'
url : url,
data : data,
async : false,
}).done(function(response){
result = response
}).fail(function(error){
console.log(error)
})
return result
}
The above function returns null when ajax is failed(error content will be shown on the console).
So it is not suitable if you want to separate operation according to error status.
In the case that you want to do some operation only when ajax is succeeded, you can handle as below.
const url = 'http://fuga.com'
response = getAjax(url, {'id':1})
if(response){
//operation when ajax is successed
.
.
.
}
ajax function for POST method
In the end, let’s create ajax function for POST method as well.
If you prepare javascript file like below, you will be able to execute ajax in the both way GET and POST from anyware.
function getAjax(url, data=null) {
return callAjax('get',url, data)
}
function postAjax(url, data) {
return callAjax('post', url, data)
}
function callAjax(type, url, data=null) {
let result = null
$.ajax({
type : type,
url : url,
data : data,
async : false,
}).done(function(response){
result = response
}).fail(function(error){
console.log(error)
})
return result
}
That is all. It was about how to save ajax result into a variable.