Javascript xmlhttprequest question

Hi,

I have a coldfusion page that includes a .js file that has the xmlhttprequest object to do ajax transactions. The GET is working and I'm getting back data but I'm having trouble looping through that data in javascript and build dynamic html elements. Here is the response I'm getting:

{studentid:"cc77xx"}
function doContacts(arg1,arg2,arg3) {
    //var sugItems = document.getElementById('countrySuggestItems');
	var targetDiv = document.getElementById('resultDiv');
	var schoolid = arg1;
	var districtid = arg2;
	var studentid = arg3;
	var urlString = 'schoolid=' + schoolid;
	urlString += '&distid=' + districtid;
	urlString += '&studid=' +  studentid;
    if(arguments.length>0) {
        // creates XMLHttpRequest object
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }

        req.open("GET", "../schools/schoolList.cfm?" + urlString, true);
        req.send(null);
        // gives the request object an event handler
        req.onreadystatechange = function() {
            if ((req.readyState == 4) && (req.status == 200)) {
                // creates an array from returned list
				//this is where I need to loop through the returned response
                var arr = req.responseText.split(',');
                if (arr.length) {
                    // formats array as an HTML table and shows the DIV
                    targetDiv.innerHTML = htmlFormat(arr);
                    targetDiv.style.display = 'block';
                }
                // No items found? Hides the DIV
                else targetDiv.style.display = 'none';
                return;
            };
        }
    }
    // Empty searchString? Hides the DIV
    else sugItems.style.display = 'none';
    return;
}

Open in new window

LVL 1
roger vAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

StingRaYCommented:
If the returned data is only "{studentid:"cc77xx"}", it is not an array. You cannot loop through this.

To parse this returned string:

eval("var obj = "+req.responseText+";");
alert(obj.studentid);

Open in new window


or if the returned is [{studentid:"cc77xx"},{studentid:"dd88yy"},...]

You can loop through the array by:

eval("var arr = "+req.responseText+";");
for(i=0;i<arr.length;i++) {
    alert(arr[i].studentid);
}

Open in new window


Hope this helps.
0
leakim971PluritechnicianCommented:
var json = '{studentid:"cc77xx"}'; // it should be : {"studentid":"cc77xx"} so I assume you receive it like a string else remove this line and the next one
json = eval( "(" + json + ")" );

for(var key in json);
var value = json[key];

alert(key);
alert(value);

Test page : http://jsfiddle.net/bEZgv/


0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
roger vAuthor Commented:
@leakim:

No that is how I get the data back. I have a coldfusion component that takes a coldfusion structure and converts it into a javascript object. So I need to be able to access it like a js object. This is how I see it in firebug's response and I've copied and pasted it exactly as is (including the braces):

{studentid:"cc77xx"}
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

Kiran SonawaneProject LeadCommented:
You can do like this
http://jsfiddle.net/bEZgv/5/
0
roger vAuthor Commented:
@sonawanekiran:

I'm staying away from jquery due to certain constraints I have. I'd like to do this with js.
0
Kiran SonawaneProject LeadCommented:
0
experts1Commented:
Try this mod!


function doContacts(arg1,arg2,arg3) {
    //var sugItems = document.getElementById('countrySuggestItems');
	var targetDiv = document.getElementById('resultDiv');
	var schoolid = arg1;
	var districtid = arg2;
	var studentid = arg3;
	var urlString = 'schoolid=' + schoolid;
	urlString += '&distid=' + districtid;
	urlString += '&studid=' +  studentid;
    if(arguments.length>0) {
        // creates XMLHttpRequest object
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }

        req.open("GET", "../schools/schoolList.cfm?" + urlString, true);
        req.send(null);
        // gives the request object an event handler
        req.onreadystatechange = function() {
            if ((req.readyState == 4) && (req.status == 200)) {
                // creates an array from returned list
				//this is where I need to loop through the returned response
                var arr = req.responseText.split(',');
                if (arr.length) {
                    // formats array as an HTML table and shows the DIV
                    var temp_str = "";
                    for (i=0;i<arr.length;i++)
                      {
                      temp_str = temp_str + arr[i] + "<br>";
                      }
                    targetDiv.innerHTML = temp_str;
                    targetDiv.style.display = 'block';
                }
                // No items found? Hides the DIV
                else {targetDiv.style.display = 'none';
                return;
            }
        }
    }
    // Empty searchString? Hides the DIV
    else sugItems.style.display = 'none';
}

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.