Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

So, I've found similar questions about JQuery in which you do not need to parse. Since I am using the AJAX XMLHttpRequest, from what I understand, the parse is necessary. The error is given on the line:

text = JSON.parse(jsonGet.responseText);

Error:

JSON.parse: unexpected end of data  
text = JSON.parse(jsonGet.responseText);

Relevant parts of the function:

function populateList(){
//retrieves list from the server, adds it to the option box
    if(toggle == 0){
        var jsonGet = new XMLHttpRequest();
        jsonGet.open("GET","./json/GetAllEvents.php",true);
        jsonGet.onreadystatechange = function () {
                text = JSON.parse(jsonGet.responseText);   //ERROR HERE
                //updating html with data received
        };
        jsonGet.send();
        toggle = 1;
    } else {}

};

The JSON returned looks like this (without the line breaks):

{"success":true,
"number_of_rows":2,
"data":[
    {"id":"7","event_name":null,"day":3,"start_time":510,"end_time":617},
    {"id":"8","event_name":null,"day":1,"start_time":510,"end_time":617}
]}

JSONLint says that the above is valid. I guess I will take a look into whether XMLHttpRequest does anything strange. Firefox continues to function (even though firebug shows the error), IE9 stops at this point though.

I'm pretty stumped. Any help is appreciated.

share|improve this question

1 Answer

up vote 3 down vote accepted

You have to check if jsonGet.readyState==4 && jsonGet.status==200 before parsing the response.

share|improve this answer
1  
Awesome, jsonGet.readyState == 4 got rid of the error. Adding the status in though causes it not to execute. The status I'm getting in a test with a .json file is 0. Thank you for the help. – douggard Feb 17 '12 at 1:34
Using the actual .php file gives status 200. Thanks again! – douggard Feb 17 '12 at 1:38
Great! The zero status could be related to your webserver versus .json files. – bfavaretto Feb 17 '12 at 1:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.