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;
}
4
  • At which point the error is coming? At page load or on a user event. Commented Aug 14, 2012 at 3:04
  • It's on page load. As soon as the page is loaded firefox web developer console gives a vague syntax error message. Commented Aug 14, 2012 at 3:05
  • 2
    @Lee Could you show your site? Commented Aug 14, 2012 at 3:08
  • @xdazz sure, www.fort-hub.com/privatechat/index.php Commented Aug 14, 2012 at 3:09

8 Answers 8

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;}
Sign up to request clarification or add additional context in comments.

6 Comments

Aha! But why has it been put on one line, when live?
I think you got it right. @Lee r u using any minification tool to do the make the code 1 liner?
No, nothing at all. I'll have to use /* */ then.
Maybe new line differences (Windows vs. Unix)?
Yes. I will suggest you to use some tool like jsmin to minify the code
|
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!

4 Comments

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!
@xdazz That missing semi will cause an error in some browsers. JSLint picks up on it as well.
@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?
@J Torres: as long as next character is closing curve bracket from outer function - yes
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.

4 Comments

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.
I do not see any problem in the script, I'll check again.
Can you share the actual unformatted script (one liner) tag from your page.
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...
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.

Comments

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 */

Comments

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.

Comments

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;
}

3 Comments

This helped a lot, thanks. Any ideas why this didn't cause a problem when run locally?
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
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.
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.

1 Comment

This seems to have nothing to do with this question. Can you explain?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.