0

Firstly, I want to confirm that this question is not duplicated with other similar questions on stackoverflow, because my question is only based on javascript, NO jquery.

I wrote website https://www.emojionline.org. Because this site is small, I don't want to use JQuery. I tried to test with Jquery to solve this problem is ok, but I only want javascript without jquery. My question is problem that return value from ajax callback function. I wrote as follows:

function loadJSON(callback) {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'emoji.json', true);
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
        }
    };
    xobj.send(null);  
}

function returnJSON(){
    var jn = '';
    loadJSON(function(response){
        jn = JSON.parse(response);
    });
    return jn;
}

var json = returnJSON();

However, the json is null when I use console.log to write? What is this problem? Please help me solve it!

2
  • ReturnJSON, where does it receive "response" from? I cannot see it in your code. Commented May 27, 2017 at 1:51
  • response is received from loadJSON callback function. Commented May 27, 2017 at 1:54

2 Answers 2

1

Synchronous request example:

function loadJSON(url) {
    var request = new XMLHttpRequest();

    request.overrideMimeType("application/json");
    request.open('GET', url, false);
    request.send();

    if (request.readyState === 4 && request.status === 200)
        return request.responseText;
}

// An example using ipify api (An IP Address API)
var json = loadJSON('https://api.ipify.org?format=json');
console.log(json);

Or asynchronous request example, using the Promise API and error event handler:

function loadJSON(url) {
    return new Promise(function (resolve, reject) {
        var request = new XMLHttpRequest();

        request.overrideMimeType("application/json");
        request.open('GET', url, true);
        request.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve({status: this.status, body: JSON.parse(this.responseText)});
                } else {
                    reject({status: this.status, body: this.responseText});
                }
            }
        };

        request.send();
    });
}

// An example using ipify api (An IP Address API)
loadJSON('https://api.ipify.org?format=json')
    .then(function (response) {
        console.log(response);
    })
    .catch(function (errorResponse) {
        console.log(errorResponse);
    });

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you. I don't check the result. But my purpose is minify the external lib. I can do successfully with jquery. However, I just want to use pure javascript only. No external library. In your code, I saw that you use external api. So I don't want to use it. Additionally, I want to return json to hold all data (I used this json to process more things).
But I'm not using any external libraries. Oo
Ok, but the second purpose :) loadJSON(function(response){ // I can processing this data in this. I receive data here successfully!!!!! But I don't want to process here. I just want to return data to my global json variable. });
Promise is pure JS, you just have to change the url to the value you want.
Oh, that means in my purpose, I need to use synchronous only. Right?
|
0

xobj.open(method, url, async, user, password);

xobj.send(null);

reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.