Add php user data to a java alert

4 posts by 3 authors in: Forums > CMS Builder
Last Post: July 31   (RSS)

Hi Ray,

You can echo php variables right into the JS.  Like:

alert("Hi <?php echo $firstName; ?>.");

One thing to look out for is if there are any double quotes in the echo-ed variable they will need to be escaped.

Hope that helps!
Robin

Robin
Programmer
interactivetools.com

Hi Ray,

What Robin suggested is the right approach, but I suggest that instead of just looking at quotes, you do a bit more to make sure things are secure. If you don't escape the values, you could open yourself up a security attack known as cross-site scripting attack (XSS). This allows someone to put some random code into the values for the user's name or address and when you echo it out to the user it will then run the attackers JavaScript as coming from you and can be used to hijack user's sessions etc. with other sites.

One way you can mitigate this issue is using the PHP function json_encode() to escape the code and make it safe for JS display. Below is an example...

<script>

  const jsUsernameSafe = <?php echo json_encode($username); ?>;

  alert(`Your username is ${jsUsernameSafe}`); //<-- Notice the use of backticks here for a template string literal (interpolation)

</script>


You may also want to just make sure that the user's name and address are not empty either an account for that. Not the greatest experience to say "Hello <blank>!" 

I hope this helps! :)

Tim Hurd
Senior Application Developer
TimHurd.com

Thanks everyone. I will give these a try!

nmsinc