You can call me a hypocrite, as I have done it in many scripts I have posted to here, but I must admit I do not like generating Javascript with PHP. It just feels so hacked together, hard to read, error-prone, and is a maintenance nightmare. Of course, that is more aimed at generating Javascript that is doing operations, conditions, etc. Obviously sometimes it is in your best interest to deliver something from PHP to the client-side for Javascript. For those cases, I suggest separating out your PHP generation from the main JS to keep the JS clean. This can be done in a clean way, by making a separate area to grab the PHP variables:
Code: Select all
echo '<script type="text/javascript">';
echo "var username = ".$user['name'].";";
echo "var level = ".$user['level'].";";
/*
now that you have these values collected at the top of your script section,
you can leverage PHP heredoc format to write clean, straight Javascript
*/
$jsScript = <<<ENDSCRIPT
//Now we can write JS freely and it will be stored in jsScript!
// sample JS script pasted in just to show how easy heredoc format makes it
// these comments will even be a part of the JS script ;)
function userid_validation(uid,mx,my)
{
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to "+my);
uid.focus();
return false;
}
return true;
}
ENDSCRIPT;
echo $jsScript;
Some may at first be sitting there blinking at the
heredoc format, but I can assure you that echoing out blocks of Javascript is really just what heredoc was created for. You create a PHP variable, use the <<< operator and then type an "ending token", which is totally arbitrary and can be anything (just make sure it isn't something you will naturally use in the JS). Then, after you have typed all the JS you want to store into the variable, you just type out the ending token again with a semi-colon, and you are out of the heredoc block and you have all that text stored in the variable (in the case above, in the $jsScript variable).
You can manually echo out some variable assignments at the top of the page concatenated with the PHP variable values, and then simply use them in the heredoc'd Javascript right below it (which I did not use the variables here, since I just copy'n'pasted this script from a website to use as an example).
I know this doesn't really focus in on the main problem at hand here, but I hope this can help some people down the line with managing dynamic Javascript blocks!