Unexpected token php in javascript

Being new to this, I'm trying to pass a variable from PHP to Javascript.

In my php page, I use a test variable:

    $testval = "x";

In my .js file:

     var exarr = ;

I've tried several things, but it seems I always get Unexpected token < when I include "

What am I doing wrong ?

Thanks !

asked Mar 9, 2016 at 16:01

AlexBAlexB

131 silver badge8 bronze badges

4

In order to use PHP code in any file, the web server has to run that file through the PHP processor. This is configured to happen by default with .php files, but not with .js files.

You could configure your server to process .js files as PHP, but that's generally unwise. At the very least, it creates a lot of unnecessary overhead for those files since most of them won't (or shouldn't) have PHP code.

Without knowing more about the structure of what you're trying to accomplish, it's difficult to advise a "best" approach. Options include (but may not be limited to):

  1. Defining that one var on a PHP page which references the JS file, thereby making it available to the JavaScript code.
  2. Putting the value in a page element somewhere that it can be accessed by JavaScript code, either as a form value or perhaps a data value.
  3. Making an AJAX request to the server to get that value (and other values) after the page has been loaded.

answered Mar 9, 2016 at 16:09

Unexpected token php in javascript

DavidDavid

195k34 gold badges191 silver badges269 bronze badges

1

If you have that in a js file (like somefile.js) then PHP isn't going to parse that file by default. In the PHP file that links to that JS you can output a script tag and the var you want like:

echo "";

And make sure your script is linked in after that code;

answered Mar 9, 2016 at 16:06

Unexpected token php in javascript

MajicBobMajicBob

4772 silver badges8 bronze badges

1

.js files are not compiled by PHP. The easiest workaround is to put the Javascript in a

44.5k15 gold badges107 silver badges146 bronze badges

answered Mar 9, 2016 at 16:06

furtivefurtive

1,5992 gold badges12 silver badges15 bronze badges

    Table of contents
  • Unexpected token error when using PHP with JavaScript
  • JavaScript Error Handling: Unexpected Token
  • Have a JavaScript Unexpected Token Error? Check Your Syntax
  • JavaScript SyntaxError – Unexpected token
  • SyntaxError: Unexpected token
  • Uncaught SyntaxError: Unexpected token

Unexpected token error when using PHP with JavaScript

Uncaught SyntaxError: Unexpected token <

JavaScript Error Handling: Unexpected Token

Unexpected end of input
expected expression, got ', '
expected expression, got ')'
expected expression, got keyword 'else'

Have a JavaScript Unexpected Token Error? Check Your Syntax

// 1
var printError = function(error, explicit) {
    console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}

try {
    // Extra comma in Math.max
    var value = Math.max(1, 2,);
    console.log(value);
} catch (e) {
    if (e instanceof SyntaxError) {
        printError(e, true);
    } else {
        printError(e, false);
    }
}
// CHROME
Uncaught SyntaxError: Unexpected token )

// FIREFOX
SyntaxError: expected expression, got ')'
var printError = function(error, explicit) {
    console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}

try {
    var name = "Bob";
    if (name === "Bob") {
        console.log(`Whew, it's just ${name}`);
    else {
        console.log("Imposter!");
    }
} catch (e) {
    if (e instanceof SyntaxError) {
        printError(e, true);
    } else {
        printError(e, false);
    }
}
// CHROME
Uncaught SyntaxError: Unexpected token else

// FIREFOX
SyntaxError: expected expression, got keyword 'else'

JavaScript SyntaxError – Unexpected token

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x" 
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"

SyntaxError
01234
SyntaxError: Unexpected token ';'

SyntaxError: Unexpected token

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"
for (let i = 0; i < 5,; ++i) {
  console.log(i);
}
// Uncaught SyntaxError: expected expression, got ';'
for (let i = 0; i < 5; ++i) {
  console.log(i);
}
function round(n, upperBound, lowerBound){
  if(n > upperBound) || (n < lowerBound){
    throw 'Number ' + String(n) + ' is more than ' + String(upperBound) + ' or less than ' + String(lowerBound);
  }else if(n < ((upperBound + lowerBound)/2)){
    return lowerBound;
  }else{
    return upperBound;
  }
} // SyntaxError: expected expression, got '||'
function round(n, upperBound, lowerBound){
  if((n > upperBound) || (n < lowerBound)){
    throw 'Number ' + String(n) + ' is more than ' + String(upperBound) + ' or less than ' + String(lowerBound);
  }else if(n < ((upperBound + lowerBound)/2)){
    return lowerBound;
  }else{
    return upperBound;
  }
}
SyntaxError: expected expression, got \"x\"\nSyntaxError: expected property name, got \"x\"\nSyntaxError: expected target, got \"x\"\nSyntaxError: expected rest argument name, got \"x\"\nSyntaxError: expected closing parenthesis, got \"x\"\nSyntaxError: expected '=>' after argument list, got \"x\"\n
for (let i = 0; i < 5,; ++i) {\n  console.log(i);\n}\n// Uncaught SyntaxError: expected expression, got ';'\n
for (let i = 0; i < 5; ++i) {\n  console.log(i);\n}\n
function round(n, upperBound, lowerBound){\n  if(n > upperBound) || (n < lowerBound){\n    throw 'Number ' + String(n) + ' is more than ' + String(upperBound) + ' or less than ' + String(lowerBound);\n  }else if(n < ((upperBound + lowerBound)/2)){\n    return lowerBound;\n  }else{\n    return upperBound;\n  }\n} // SyntaxError: expected expression, got '||'\n
function round(n, upperBound, lowerBound){\n  if((n > upperBound) || (n < lowerBound)){\n    throw 'Number ' + String(n) + ' is more than ' + String(upperBound) + ' or less than ' + String(lowerBound);\n  }else if(n < ((upperBound + lowerBound)/2)){\n    return lowerBound;\n  }else{\n    return upperBound;\n  }\n}\n

Uncaught SyntaxError: Unexpected token

// including jquery.js
// this script is myapp.js

// Get the json data instead of making a request
$(".mybtn").on("click",function(e){
    // Stop the default behaviour.
    e.preventDefault();
    //
    var jsonUrl = this.href + "&json=1";

    $.ajax({
        url: jsonUrl,
        type: "json",
        method: "get",

        success: function(data){
            // do something with the data
            alert(data);
        }
    });

});



...

             ^------------------- does not exist.

   
      
   
   
      

Let appID = '905925d53d24566c39eef30036b22d33';
Let units = 'imperial';
Let searchMethod = 'Zip';

function searchWeather(searchTerm) {
    fetch(`http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&appID=${appID}&units=${units}`).then(result => {
    return result.json();
    }).then(result => {
    init(result);
    })
    // fetch api a url bcz its a 
    //call to get information from the API. This link is a queue so searchMethod(a parameter)= searchTerm (parameter value) 
    //wait until we get the info from url/server we use ".then(result=>" 
    //and next converting into json next parse the info which we get from server in init 
}

function init(resultFromServer) {
    console.log(resultFromServer);
}
document.getElementById('searchbtn').addEventListener('click', () => {
    let searchTerm = document.getElementById('searchInput').value;
    if (searchTerm)
    searchWeather(searchTerm);
})
Uncaught SyntaxError: Unexpected token { 0.chunk.js:105
Uncaught SyntaxError: Use of const in strict mode.  main.chunk.js:268 


    All Fours Tournament
    
        

All Fours

let express=require('express');
let http=require('http');
let fs=require('fs');

let handleRequest=(request, response)=>{
    response.writeHead(200, {
        'Content-Type':'text/html'
    });
    fs.readFile('allFours.html', null, function(error, data) {
        if(error){
            response.writeHead(404);
            response.write('File Not Found');
        } else {
            response.write(data);
        }
        response.end();
    });
}
http.createServer(handleRequest).listen(4040);
console.log('Server is listening on port 4040');
//add click listeners to squares 
squares[i].addEventListener("click", function(){
changeColors(clickedColor);
const cartBtn = document.querySelector(".cart-btn");
const closeCartBtn = document.querySelector(".close-cart");
const clearCartBtn = document.querySelector(".clear-cart");
const cartDOM = document.querySelector(".cart");
const cartOverlay = document.querySelector(".cart-overlay");
const cartItems = document.querySelector(".cart-items");
const cartTotal = document.querySelector(".cart-total");
const cartContent = document.querySelector(".cart-content");
const ProductsDOM = document.querySelector(".products-center");
// cart
let cart = [];

// getting the products
class Products{
async getProducts()
{
        try {
            let result = await fetch("products.json");
            let data = await result.json();
            let products = data.items;
            products = products.map(item => {
                const {title,price} = item.fields;
                const id = item.sys;
                const image = item.fields.image.fields.file.url;
                return {title,price,id,image}
            });
            return products;
        }
        catch (error) {
        console.log(error);
        }
  }
}

// display products

class UI {
displayProducts(products){
let result = "";
products.forEach(product => {
    result +=
    //single product 
    
// error comes here

${product.title}

'

$${product.price}

}); ProductsDOM.innerHTML = result ; } } // local storage class Storage{ } document.addEventListener("DOMContentLoaded", () => { let ui = new UI(); let products = new Products(); products.getProducts().then(products => ui.displayProducts(products)); });


    
    
    
    
    <?php if ($_GET['controller']!='admin') require "title.view.php"; ?>
 $( document ).ready( function(){
// Call counter and set autostart to false
$( .stats ).count( {
    autoStart: false 
});

// Call horizon
$( '.stats' ).horizon({
 recurring: true, 

// Start counter once element is in view
inView: function(){ 
        $( '.stats' ).each( function(){
        var count = $( this ).data( 'counter' );
            count.startCount();
        });
    },

// Clear counter once element is out of view
outOfView:  function(){ 
        $( '.stats' ).each( function(){
        var count = $( this ).data( 'counter' );
            count.clearCount();
        });
    }
});
});

Javascript – Uncaught SyntaxError: Unexpected token : – Code Utility

{"votes":47,"totalvotes":90}
vote.each(function(e){
  e.set('send', {
    onRequest : function(){
      spinner.show();
    },
    onComplete : function(){
      spinner.hide();
    },
    onSuccess : function(resp){
      var j = JSON.decode(resp);
      if (!j) return false;
      var restaurant = e.getParent('.restaurant');
      restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
      $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
      buildRestaurantGraphs();
    }
  });

  e.addEvent('submit', function(e){
    e.stop();
    this.send();
  });
});
$ret['foo'] = "bar";
finish();

function finish() {
    header("content-type:application/json");
    if ($_GET['callback']) {
        print $_GET['callback']."(";
    }
    print json_encode($GLOBALS['ret']);
    if ($_GET['callback']) {
        print ")";
    }
    exit; 
}
vote.each(function(element){                
  element.addEvent('submit', function(e){
    e.stop();
    new Request.JSON({
      url : e.target.action, 
      onRequest : function(){
        spinner.show();
      },
      onComplete : function(){
        spinner.hide();
      },
      onSuccess : function(resp){
        var j = resp;
        if (!j) return false;
        var restaurant = element.getParent('.restaurant');
        restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
        $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
        buildRestaurantGraphs();
      }
    }).send(this);
  });
});
var total = $.parseJSON(response);
{"votes":47,"totalvotes":90}
"votes":47,"totalvotes":90
var resp = '{"votes":47,"totalvotes":90}';
eval(resp);

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\Projects\rwp\demo\en\super\ge.php on line 54
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}
error_reporting(E_ERROR | E_PARSE);
onSuccess : function(resp){  
   alert(resp);  
}
onSuccess : function(resp){  
   var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp); 
}
Undefined variable: errCapt in .... on line65
{"firstName":"John", "lastName":"Doe"}
window.location = https://google.com;
window.location = "https://google.com";
@RequestMapping(name="/private/updatestatus")
 @RequestMapping("/private/updatestatus")
 @RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)
   `var  fs = require('fs');
    var fs.writeFileSync(file, configJSON);`
xblock.js:158 SyntaxError: Unexpected token '=>'
at eval ()
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object. (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'\n    at eval ()\n    at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)\n    at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)\n    at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)\n    at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)\n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)\n    at Object. (http://localhost:18010/static/studio/bundles/commons.js:5057:25)\n    at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)\n    at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)\n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"
zzz
... onclick="window.location = '?dir=zzz'" ...

Next Lesson PHP Tutorial

What is Unexpected token in JavaScript?

The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.

What is unexpected token in PHP?

Unexpected – This means the code is missing a character and PHP reaches the end of the file without finding what it's looking for. The error will include information at the end that explains what it saw that was unexpected.