Got 'undefined' when trying to get a field from JsonResponse

created at 12-28-2021 views: 2

problem

Bellow is a code snippt of my web editor used to upload image with XMLHttpRequest:

var formdata = new FormData();
formdata.append('image', image);
var ajax = new XMLHttpRequest()
ajax.open('POST',uploadLocation,true);
ajax.send(formdata);
ajax.onreadystatechange = function(){
    if(ajax.readyState === 4){
        if(ajax.status === 200){
            if(ajax.response.error){
                console.log(ajax.response.error);
            } else {
                console.log(ajax.response);
                console.log(ajax.response.url);
            }
        } else {
            alert("failed to upload (,,•́ . •̀,,)");
        }
    }
}

based on the above code, if the image is uploaded successfully, we would get two message from:

console.log(ajax.response);
console.log(ajax.response.url);

test result:

{ "success": true, "url": "/media/Snipaste_2021-06-29_21-15-40_fV8lVoX.png" }
undefined

I found that I could not get access to the value of the url field.

solution

after some research, I noticed that the response is not an Json object! To access the value of url with the dot operator (ajax.response.url), we need to convert the response to an JSON object with JSON.parse() method:

modify the above example:

// convert first here:
 var response = JSON.parse(ajax.response)

 console.log(response);
 console.log(response.url);

test result:

Object { success: true, url: "/media/Snipaste_2021-06-29_21-15-40_fV8lVoX.png" }

/media/Snipaste_2021-06-29_21-15-40_fV8lVoX.png

now well done!

created at:12-28-2021
edited at: 12-28-2021: