Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
Illegal token in synchronous Javascript sent back from PHP response, regards cross site widget development

I have a widget on the test subject website; below.

<div id="widget"></div>
<script src="http://www.project.com/api/?api=bXOIo4ERTaZt-a5b71a1c" type="text/javascript"></script>
<script>
     
    initialise(); 
    
</script>

The widget communicates with the project website without any hitches. Except, when I have the PHP in the project website; like so.

function initialise() { 
    var container = 'widget'; 
    var ele = document.getElementById( container );
    
    var response = "<?php foreach( $this -> get( 'api:bestsellers' ) as $record ): ?><p><?php echo $record -> get( 'title' ); ?>, <?php echo $record -> get( 'format_price' ); ?></p><br><?php endforeach; ?>";

    ele.innerHTML = response;
}

This is the PHP on the project website, called by the widget. This works grand except when I put the PHP on a new line (for example indention and so on) I get an error on the developer tools; like so.

var response = "
<?php foreach( $this -> get( 'api:bestsellers' ) as $record ): ?><p><?php echo $record -> get( 'title' ); ?>, <?php echo $record -> get( 'format_price' ); ?></p><br><?php endforeach; ?>";

I get this: "Uncaught SyntaxError: Invalid or unexpected token"

Points to note are: 1) I am using synchronous Javascript for a reason and asynchronous Javascript/AJAX isn't an option, because I need multiple widgets on the same page, 2) my field of expertise is PHP and not Javascript, 3) I have tried (Javascript) string replacement on non UTF8 characters, line breaks and tabs, etc and invisible characters on the response.

Kind of lost as to why I can't use indention on the PHP block, any suggestions to get the response back to the widget in one piece, with no errors or faults? Thanks.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The error happens because the variable response's string is on multiple lines. To make a string multiple lines, you use backticks. Try this:

var response = `
<?php foreach( $this -> get( 'api:bestsellers' ) as $record ): ?><p><?php echo $record -> get( 'title' ); ?>, <?php echo $record -> get( 'format_price' ); ?></p><br><?php endforeach; ?>`;
// Did not give an error!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!