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