[javascript] javascript unexpected identifier

I am trying to compress my JavaScript code to get less traffic on my site. It has been working fine, but now I came across an error I can't resolve.

I turned my ajax function into one line:

function(){if(xmlhttp.readyState==4&&xmlhttp.status==200){document.getElementById("content").innerHTML=xmlhttp.responseText;}}xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();}

But the chrome console tells me there is an unexpected identifier on this line. Firefox says there is an semicolon missing on this line.

I have been trying to figure out what is wrong, but I can't find the error, can someone help me with this?

This question is related to javascript

The answer is


Yes, you have a } too many. Anyway, compressing yourself tends to result in errors.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

Use Closure Compiler instead.


Either remove one } from end of responseText;}} or from the end of the line


I recommend using http://jsbeautifier.org/ - if you paste your code snippet into it and press beautify, the error is immediately visible.


In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:

function(){
  if(xmlhttp.readyState==4&&xmlhttp.status==200){
    document.getElementById("content").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}

There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()

And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?


It looks like there is an extra curly bracket in the code.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}