0

Introduce the problem before you post any code:

I have a simple JavaScript code and it's giving me an unexpected token error. It's code that I'm trying to convert from PHP to JavaScript for use in a Phonegap application.

Specifically it is the line that declares the $ex_data variable. And it says the unexpected token is the section between the $system and $galaxy variables.

Code

for ($galaxy = 1; $galaxy < 21; $galaxy++){
            for ($system = 1; $system < 601; $system++){
                var $ex_data = '{"planet_id":-1,"sid":'.$system.',"language":"en","gid":'.$galaxy.'}';
                var $url = "http://54.193.106.113/ING004/android1/WebServer/Web/sogame/newControl/nmUniverse/getUniverse?sign=".toUpperCase($sign);     

            }
        }

CLEAR QUESTION:

How do I fix the line so that it is valid?

5
  • 1
    In JS we use + to concat string literals.
    – Leo
    Jan 1, 2015 at 2:31
  • 1
    Usually you also don't prefix your variables with $ in JS (even though it's a valid character in a variable name in JS). Jan 1, 2015 at 2:36
  • 1
    And please... NEVER use string concatenation to build JSON data - it's a terrible thing in both PHP and JavaScript. In PHP, create an array and json_encode() it. In JavaScript, create an object and JSON.stringify() it. Jan 1, 2015 at 2:37
  • Thanks for those tips! If I may ask, why is concatenation so bad for it?
    – user4333143
    Jan 1, 2015 at 2:41
  • @ZappTBrannigan: you probably won't be sent to hell for it, but it's usually better to use JSON.stringify() as you'll never accidentally make any mistakes like missing a closing brace or comma -- this is more important the larger the object is. Jan 1, 2015 at 4:59

2 Answers 2

1

You are confusing PHP concatenation with JavaScript (C) concatenation.

for ($galaxy = 1; $galaxy < 21; $galaxy++) {
        for ($system = 1; $system < 601; $system++) {
            var $ex_data = '{"planet_id":-1,"sid":'
                         . $system . ',"language":"en","gid":' . $galaxy.'}';
            var $url = "http://54.193.106.113/ING004/android1/WebServer/Web/sogame/newControl/nmUniverse/getUniverse?sign="
                       .toUpperCase($sign);     
        }
    }

Change the ".s" to "+s".

var $ex_data = '{"planet_id":-1,"sid":'
             + $system + ',"language":"en","gid":' + $galaxy + '}';

or alternatively

var $ex_data = JSON.stringify({
    "planet_id" : -1,
    "sid"       : $system,
    "language"  :"en",
    "gid"       : $galaxy
});

Also, as pointed out below, change .toUpperCase($sign); -> + $sign.toUpperCase();

1
  • 1
    toUpperCase($sign) -- it is mistake! For JS it has to be $sign.toUpperCase(). You should fix it! Jan 1, 2015 at 3:08
0
var $ex_data = '{"planet_id":-1,"sid":' + $system + ',"language":"en","gid":' + $galaxy +'}';
var $url = "http://54.193.106.113/ING004/android1/WebServer/Web/sogame/newControl/nmUniverse/getUniverse?sign=" + $sign.toUpperCase();