How to use Javascritp only to populate Object with Ajax Get request response text?

Good afternoon my friends:

I have the following code which creates a request and then uses the
request to Get data via AJAX.

How do I return the responseText to a JavaScript Object which I can access outside of the function making the request? I need to use JavaScript only, no JQuery.

The data source is formatted as JSON, here is a sample:

[{"City":"KABUL",
  "Continent":"ASIA",
  "Country":"AFGHANISTAN",
  "CountryAbbr":"AF",
  "CountryId":"102120"}]

How do I return the data to an object so that I am able to access the data for display purposes, e.g on an HTML page?

Code:

<script type="text/javascript">

function createXHR(){

    if ( typeof XMLHttpRequest != 'undefined' ){

        return new XMLHttpRequest();

        } else if ( typeof ActiveXObject !=  'undefined' ){

            if (typeof arguments.callee.activeXString != 'string'){

                var versions = ['MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.3.0','MSXML2.XMLHttp'], i, len;

                for (i=0,len=versions.length; i < len; i++){

                    try {new ActiveXObject(versions[i]);

                    arguments.callee.activeXString = versions[i];

                    break;

                    } catch (ex){

                }
            }
        }

    return new ActiveXObject(arguments.callee.activeXString);

    } else {

    throw new Error('No XHR object available.');

    }
}


var xhr = createXHR();
xhr.onreadystatechange = function(){

    if (xhr.readyState == 4){

        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){

            //Retrun the response text to an Object
            alert(xhr.responseText);

            } else {

                alert('Request was unsuccessful: ' + xhr.status);

                }

        }

    };

xhr.open('get', 'myurl/', true);
xhr.setRequestHeader('Content-Type', 'application/json');   
xhr.send(null);

</script>

Finally, I attempted to populate the object like this:

var dataObject = JSON.parse(xhr.responseTex);

And access like this: For example:

console.log(dataObject[0].City);

I get the following error:

Uncaught TypeError: Cannot read property ‘Country’ of undefined.

Thanks in advance.

To use JSON.parse you need the value to be able to be parsed as JSON and what you are returning isn’t JSON - it is an array containing one entry that is JSON.

Please forgive my confusion, the data comes from a Web service via the URL. The service serialized the data and it is explicitly indicated as JSON format.

Are you saying that the data is not JSON and is this related to the error?

Thanks

JSON is allowed to be an array too, according to the MDN JSON syntax standards, and I see nothing different from the ECMA-404 JSON standard either.

Are you thinking that JSON has to be contained entirely within an object?

The JSON Validator linked from http://json.org says that the OP’s JSON is valid too.

[quote=“Paul_Wilkins, post:4, topic:204079, full:true”]

Hi Paul.
I am able to alert or write the result (responseText) to console. The issue I am having is how to return the response text to an object that I can than access out side of the function so that I
am able to write the data to html elements.

Any directions or input will be appreciated.

Always, thanks.

It’s hard to give any useful direction when we don’t know what’s responsible for the problem.

Can you please direct us to the web service that you are using to obtain the data? This will help us to work out where to best spend our efforts.

Yes I was and I have come across situations where wrapping it in an array caused problems too - but I can’t remember where I saw that now it was a while ago.

Checking section 15.12.1.2 of the standards (and not just relying on a third party source such as MDN which has been known to have errors in it) it appears that objects and arrays are not all that JSON can consist of.

So I have learnt something new about JSON today.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.