[Javascript]How to save ajax result into a variable


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})

if(response){
    //operation when ajax is successed
    .
    .
    .
}
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 and error content will be shown on the console. 





Automatic conversion from JSON to object

In Ajax, it is common to receive JSON as a response and convert it to an object using JSON.parse for further use. By modifying the code inside the done method as follows, you can conveniently receive the response as-is if it is in text format, or parse it with JSON.parse if it is in JSON format.

function getAjax(url, data=null) {
    let result = null  
    $.ajax({
        type  : 'get',
        url   : url,
        data  : data,
        async : false,
    }).done(function(response){
        try{                                // fix
            result = JSON.parse(response)   // fix
        }catch{                             // fix
            result = response               // fix
        }                                   // fix
    }).fail(function(error){
        console.log(error)
    })
    return result
}





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){
        try{
            result = JSON.parse(response)
        }catch{
            result = response
        }  
    }).fail(function(error){
        console.log(error)
    })
    
    return result
}






plain JavaScript version

I will also provide a function for achieving the same thing using plain JavaScript.

You can perform AJAX communication using the XMLHttpRequest class in plain JavaScript.
When you want to perform synchronous communication with the XMLHttpRequest class, you set the third argument of the open method to false.

function callAjax(type, url, data=null) {
    let result = null
    let params = new URLSearchParams( data ).toString()
    let contentType = 'application/x-www-form-urlencoded'
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if(xhr.readyState != 4){ return }
        if(xhr.status == 200){
            try{
                result = JSON.parse(xhr.responseText)
            }catch{
                result =  xhr.responseText
            }   
        } else {
            console.log('XMLHttpRequestエラー' + xhr.status + ' : ' + xhr.statusText)
        }
    }
    if(type == 'get'){
        url = url + '?' + params
    }
    xhr.open(type, url, false)
    xhr.setRequestHeader('Content-type', contentType)
    xhr.send(params)
    
    return result
}






That is all. It was about how to save ajax result into a variable.

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply

*