How to pass PHP variables as parameters to Javascript UDF?

I know that PHP is server side, and Javascript is client side, but I have a case where I need to pass 2 PHP variables as parameters to a Javascript function that updates some text on screen.

Basic PHP skeleton code is:

   echo'<input type="text" onchange="updatefn(var1, var2)">';

In this case var1 is a numeric and var2 is the id of the div holding the text that needs changing.

If I change var1 and var2 to actual values it works ok, but in the program I have two variables $var1 and $var2 that are.the ones that actually needed to be passed.

I have seen examples where one PHP variable is passed, albeit from an HTML statement not from a PHP echo statement, but am having problems trying to pass the two variables.
Many thanks

PHP is client-side only. Therefore, it can post data into Javascript before it is sent to the browser.
Just insert it where you want it. Loosely like this:

echo '<input type="text" onchange="updatefn(' . $var1 . ',' . $var2 . ")">';

Or, you can use str_replace functions to replace them, but, it is easier just to store them as needed.
Hope that helps…

Thanks, will give it a try.

Just one thing I noticed should the double quotation mark before the closing bracket be a single quote?

Yes, typed it too fast.

Sponsor our Newsletter | Privacy Policy | Terms of Service