7

Ok, so you know the error, but why on earth am I getting it?

I get no errors at all when this is run locally, but when I uploaded my project I got this annoying syntax error. I've checked the Firebug error console, which doesn't help, because it put all my source on the same line, and I've parsed it through Lint which didn't seem to find the problem either - I just ended up formatting my braces differently in a way that I hate; on the same line as the statement, bleugh.

function ToServer(cmd, data) {
    var xmlObj = new XMLHttpRequest();
    xmlObj.open('POST', 'handler.php', true);
    xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlObj.send(cmd + data);
    xmlObj.onreadystatechange = function() {
        if(xmlObj.readyState === 4 && xmlObj.status === 200) {
            if(cmd == 'cmd=push') {
                document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
            }
            if(cmd == 'cmd=pop') {
                document.getElementById('messages').innerHTML += xmlObj.responseText;
            }
            if(cmd == 'cmd=login') {
                if(xmlObj.responseText == 'OK') {
                    self.location = 'index.php';
                }
                else {
                    document.getElementById('response').innerHTML = xmlObj.responseText;
                }
            }
        }
    }
}

function Login() {
    // Grab username and password for login
    var uName = document.getElementById('uNameBox').value;
    var pWord = document.getElementById('pWordBox').value;
    ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);
}


// Start checking of messages every second
window.onload = function() {
    if(getUrlVars()['to'] != null) {
        setInterval(GetMessages(), 1000);
    }
}

function Chat() {
    // Get username from recipient box
    var user = document.getElementById('recipient').value;
    self.location = 'index.php?to=' + user;
}

function SendMessage() {
    // Grab message from text box
    var from = readCookie('privateChat');
    var to = getUrlVars()['to'];
    var msg = document.getElementById('msgBox').value;
    ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg);
    // Reset the input box
    document.getElementById('msgBox').value = "";
}

function GetMessages() {
    // Grab account hash from auth cookie
    var aHash = readCookie('privateChat');
    var to = getUrlVars()['to'];
    ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
    var textArea = document.getElementById('messages');
    textArea.scrollTop = textArea.scrollHeight;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lee
  • 3,869
  • 12
  • 45
  • 65

8 Answers8

20

The problem is your script on your server is in one line, and you have comments in it. The code after // will be considered as comment. That's the reason.

function ToServer(cmd, data) { var xmlObj = new XMLHttpRequest(); xmlObj.open('POST', 'handler.php', true); xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlObj.send(cmd + data); xmlObj.onreadystatechange = function() { if(xmlObj.readyState === 4 && xmlObj.status === 200) {  if(cmd == 'cmd=push') {  document.getElementById('pushResponse').innerHTML = xmlObj.responseText;  }  if(cmd == 'cmd=pop') {  document.getElementById('messages').innerHTML += xmlObj.responseText;  }  if(cmd == 'cmd=login') {  if(xmlObj.responseText == 'OK') {   self.location = 'index.php';  }  else {   document.getElementById('response').innerHTML = xmlObj.responseText;  }  }   } };}function Login() { // Grab username and password for login var uName = document.getElementById('uNameBox').value; var pWord = document.getElementById('pWordBox').value; ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);}// Start checking of messages every secondwindow.onload = function() { if(getUrlVars()['to'] != null) { setInterval(GetMessages(), 1000); }}function Chat() { // Get username from recipient box var user = document.getElementById('recipient').value; self.location = 'index.php?to=' + user;}function SendMessage() { // Grab message from text box var from = readCookie('privateChat'); var to = getUrlVars()['to']; var msg = document.getElementById('msgBox').value; ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg); // Reset the input box document.getElementById('msgBox').value = "";}function GetMessages() { // Grab account hash from auth cookie var aHash = readCookie('privateChat'); var to = getUrlVars()['to']; ToServer('cmd=pop','&account=' + aHash + '&to=' + to); var textArea = document.getElementById('messages'); textArea.scrollTop = textArea.scrollHeight;}function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null;}function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars;}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
xdazz
  • 158,678
  • 38
  • 247
  • 274
2

You're missing a semi-colon:

function ToServer(cmd, data) {
    var xmlObj = new XMLHttpRequest();
    xmlObj.open('POST', 'handler.php', true);
    xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlObj.send(cmd + data);
    xmlObj.onreadystatechange = function() {
        if(xmlObj.readyState === 4 && xmlObj.status === 200) {
            if(cmd == 'cmd=push') {
                document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
            }
            if(cmd == 'cmd=pop') {
                document.getElementById('messages').innerHTML += xmlObj.responseText;
            }
            if(cmd == 'cmd=login') {
                if(xmlObj.responseText == 'OK') {
                    self.location = 'index.php';
                }
                else {
                    document.getElementById('response').innerHTML = xmlObj.responseText;
                }
            }           
        }
    }; //<-- Love the semi
}

Additional missing semi-colon:

// Start checking of messages every second
window.onload = function() {
    if (getUrlVars()['to'] != null) {
        setInterval(GetMessages(), 1000);
    }
}; //<-- Love this semi too!
Jaime Torres
  • 10,365
  • 1
  • 48
  • 56
  • How come this wasn't picked up when I ran it on my local server? This still doesn't solve the error by the way :/ Sorry, no medal for you! – Lee Aug 14 '12 at 03:06
  • @xdazz That missing semi will cause an error in some browsers. JSLint picks up on it as well. – Jaime Torres Aug 14 '12 at 03:11
  • @zerkms Please extrapolate. Are you saying you can assign a variable to a value, and are not required to end the statement with a semi-colon? – Jaime Torres Aug 14 '12 at 03:19
  • 1
    @J Torres: as long as next character is closing curve bracket from outer function - yes – zerkms Aug 14 '12 at 03:20
2

I think you can adapt divide and conquer methodology here. Remove last half of your script and see whether the error is coming. If not, remove the first portion and see. This is a technique which I follow when I get an issue like this. Once you find the half with the error then subdivide that half further till you pin point the location of the error.

This will help us to identify the actual point of error.

I do not see any problem with this script.

This may not be the exact solution you want, but it is a way to locate and fix your problem.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I understand. It has always been an option, just wanted a fresh set of eyes on the script to make sure I wasn't doing something daft. – Lee Aug 14 '12 at 03:11
  • I do not see any problem in the script, I'll check again. – Arun P Johny Aug 14 '12 at 03:12
  • Can you share the actual unformatted script (one liner) tag from your page. – Arun P Johny Aug 14 '12 at 03:13
  • AWESOME - just applied divide and conquer to a 5000 line script - 10 minutes, where I was lost before; it is very logical however sometimes focussing (on debugging) makes blind... – Quicker Oct 17 '14 at 20:16
2

Enter image description here

It looks like it's being interpreted as being all on one line. See the same results in Fiddler 2.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JayC
  • 7,053
  • 2
  • 25
  • 41
2

This problem could do due to your JavaScript code having comments being minified. If so and you want to keep your comments, then try changing your comments - for example, from this:

// Reset the input box

...to...

/* Reset the input box */

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253
1

It seems there should be added another semicolon in the following code too:

// Start checking of messages every second
window.onload = function() {
    if(getUrlVars()['to'] != null) {
        setInterval(GetMessages(), 1000);
    }
};  <---- Semicolon added

Also here in this code, define the var top of the function

function readCookie(name) {
    var i;
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mujahid
  • 1,227
  • 5
  • 32
  • 62
  • This helped a lot, thanks. Any ideas why this didn't cause a problem when run locally? – Lee Aug 14 '12 at 03:19
  • I'm not sure exactly, but in my IDE I've enabled the Javascript Debugger and it shows those are the errors. I'm using Aptana Studio 3 – Mujahid Aug 14 '12 at 03:21
  • Hm I think I found a clue... I'm using notepad++ and have until recently used my cpanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – Lee Aug 14 '12 at 03:31
1

"Hm I think I found a clue... I'm using Notepad++ and have until recently used my cPanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – "

I believe this was your problem (you probably solved it already). I just tried a different FTP client after running into this stupid bug, and it worked flawlessly. I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

Adding a note: very strangely this error was there very randomly, with everything working fine.

Syntax error missing } after function body | At line 0 of index.html

It appears that I use /**/ and // with some fancy Unicode character in different parts of my scripts for different comments.

This is useful to me, for clarity and for parsing.

But if this Unicode character and probably some others are used on a JavaScript file in comments before any JavaScript execution, the error was spawning randomly.

This might be linked to the fact that JavaScript files aren't UTF-8 before being called and read by the parent page. It is UTF-8 when the DOM is ready. I can't tell.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
NVRM
  • 11,480
  • 1
  • 88
  • 87