Zeynel
Zeynel

Reputation: 13525

Javascript Uncaught SyntaxError: Unexpected identifier error in Chrome debugger

I am adapting the XMLHttpRequest from this tutorial:

var request = new XMLHttpRequest();  
request.open('GET', 'http://www.mozilla.org/', true);  
request.onreadystatechange = function (aEvt) {  
  if (request.readyState == 4) {  
     if (request.status == 200)  
       console.log(request.responseText)  
     else  
       console.log('Error', request.statusText);  
  }  
};  
request.send(null);

My code is:

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
  if (xhr.readyState == 4) {
      if (xhr.status == 200) 
          console.log("request 200-OK");
          chrome.browserAction.setBadgeText ( { text: "done" } );
      else
          console.log("connection error");
          chrome.browserAction.setBadgeText ( { text: "ERR" } );
      setTimeout(function () {
      chrome.browserAction.setBadgeText( { text: "" } );
      }, 2000);
  }        
}        
xhr.send(formData);

But Chrome debugger gives a Uncaught SyntaxError: Unexpected identifier error on the else. What am I doing wrong? Thanks!

Upvotes: 1

Views: 17057

Answers (1)

GNi33
GNi33

Reputation: 4509

You are missing the closing } before and the opening { after the else, as well as the other ones in your if-else - statement.

It works on your tutorial code, because there's only one line in the if-else - statement. When there are multiple lines, you have to block them correctly. (I personally recommend to do this always, even if there's just one line of code. In my opinion it adds to readability and you will not have problems, when you decide to minify your code one day)

Try this:

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
  if (xhr.readyState == 4) {
      if (xhr.status == 200){
          console.log("request 200-OK");
          chrome.browserAction.setBadgeText ( { text: "done" } );
      }else{
          console.log("connection error");
          chrome.browserAction.setBadgeText ( { text: "ERR" } );
      setTimeout(function () {
      chrome.browserAction.setBadgeText( { text: "" } );
      }, 2000);
    }
  }        
};    
xhr.send(formData);

Upvotes: 2

Related Questions