Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: "Syntax error missing } after function body"

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;
}
like image 878
Lee Avatar asked Aug 14 '12 03:08

Lee


8 Answers

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;}
like image 68
xdazz Avatar answered Sep 28 '22 23:09

xdazz


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!
like image 24
Jaime Torres Avatar answered Sep 29 '22 00:09

Jaime Torres


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.

like image 43
Arun P Johny Avatar answered Sep 29 '22 01:09

Arun P Johny


Enter image description here

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

like image 23
JayC Avatar answered Sep 28 '22 23:09

JayC


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

like image 33
ban-geoengineering Avatar answered Sep 29 '22 00:09

ban-geoengineering


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.

like image 39
NVRM Avatar answered Sep 28 '22 23:09

NVRM


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;
}
like image 41
Mujahid Avatar answered Sep 29 '22 00:09

Mujahid


"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.

like image 28
Michelle Audrey Sanders Avatar answered Sep 29 '22 00:09

Michelle Audrey Sanders