this code displays cat,is this a valid way of equating javascript variables to php variables, 1:Valid is maybe not the word I would" name="description" /> this code displays cat,is this a valid way of equating javascript variables to php variables, 1:Valid is maybe not the word I would" />
62898

Equating Javascript and PHP Variables

Question:

<?php $a="cat"; $html=<<<HTML <html> <script> var b ="$a"; document.write(b); </script> </html> HTML; echo $html;?>

this code displays cat,is this a valid way of equating javascript variables to php variables,

Answer1:

Valid is maybe not the word I would use. Does it work, is a more important question to me. In general, because PHP runs at the server before returning the page to the browser, which then interprets and executes JavaScript, you can definitely write in variables that JS will use. So will this work? sure.

Is there a better way of doing this? Yes, absolutely. In general you don't want blocks of executable JS statements residing in a PHP script. This just muddles things up and makes them very tough to maintain. I would prefer to actually have JS request the value through an AJAX call to a PHP service. If you must use this approach, I would still separate concerns a little better.

EDIT: This works for me:

<html> <head> <title>PHP-JS Writer</title> </head> <body> <?php $a = "cat"; echo "<script>var b = '$a'</script>"; ?>

Writing JS variables with PHP

<script> alert(b); </script> </body> </html>

Answer2:

If you want to convert PHP variables to Javascript, you can best use json_encode, because it handles all escaping and such for you:

<?php $a = "some value"; ?> <script> var a = <?php echo json_encode($a); ?>; console.log(a); </script>

You can use this for more complex structures as well:

<script> var a = <?php echo json_encode(array('property' => 'value')); ?>; console.log(a.property); </script>

Of course, PHP is evaluated server side and JavaScript client side, so there is no way to let JavaScript "talk to PHP" as if it were in the same execution scope, which they aren't by definition. This is a very basic concept of serialization and deserialization to have one platform use the data from another.

You could implement asynchronous requests ("ajax") to retrieve the data from the server, and have the server respond in JSON as well, so the Javascript engine can parse the response contents natively. This has the upside of your client to be able to re-retrieve the data without reloading, but the downside of needing to do (at least) two HTTP requests.

Recommend

  • How to preserve alias property while signing app?
  • 1º Day of Daylight Saving Time Java and JS showing a different behavior
  • How to package a jar and all dependencies within a new jar with maven
  • File random access in J2ME
  • How to generate an asynchronous reset verilog always blocks with chisel
  • Unable to run SDL program in Eclipse but able to do so in Windows Explorer
  • How to send control C to Mac Terminal using python?
  • CKeditor stripping font tags instead of converting to span
  • Basic defensive programming [duplicate]
  • Python function to read variable length blocks of data from file while open
  • Draw half infinite lines?
  • Portable JRE on Linux - possible?
  • How do I Dispose a HttpResponseMessage in my Web Api Method?
  • I am receiving HibernateException “No Hibernate Session bound to thread, and configuration does not
  • How can Delete be both a DDL and a DML statement
  • How to retrieve information from antrun back to maven?
  • How to synchronize jQuery dialog box to act like alert() of Javascript
  • pyodbc doesn't report sql server error
  • How can the INSERT … ON CONFLICT (id) DO UPDATE… syntax be used with a sequence ID?
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • Swift: Switch statement fallthrough behavior
  • How to install a .deb file on a jailbroken iphone programmatically?
  • req.body is undefined - nodejs
  • HTML download movie download link
  • Resize panoramic image to fixed size
  • Volusion's generic SQL folder, functionality
  • Updating server-side rendering client-side
  • Modifying destination and filename of gulp-svg-sprite
  • htaccess rewriting URLs with multiple forward slashes
  • Importing jscolor library in angular 2
  • Display Images one by one with next and previous functionality
  • Web-crawler for facebook in python
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • A cron job substitute?
  • C# - Getting references of reference
  • How to set the response of a form post action to a iframe source?
  • How do you join a server to an Active Directory (domain)?
  • coudnt use logback because of log4j
  • Setting background image for body element in xhtml (for different monitors and resolutions)