Monday, May 11, 2009

Embedding JavaScript within PHP Script

Actually the title of this post should be "Embedding PHP variables within JavaScript which is embedded within echoed HTML within PHP."

Consider this block of code:

echo '[tag]body background="../files/backgroundfade1.jpg"
onLoad="document.getElementById(\'search\').focus();
document.getElementById(\'search\').value=\' '.$_POST[search].'\';"
[tag]';

This little block of code solves a really difficult problem, which is how to have a PHP-generated page of code automatically put the cursor (focus) into the search field at the END of the text in the field (not the beginning). Notice that the echoed HTML within PHP has to be enclosed in single quotes, and the JavaScript embedded in the HTML has to be enclosed in double-quotes, and within that JavaScript one needs additional embedded single quotes to enclose names and data. But if I just use the single quotes I inadvertently escape out of my original HTML statement. THE SECRET IS TO USE BACK_SLASHES BEFORE THE EMBEDDED SINGLE QUOTES to preserve JavaScript environment, then you can immediatedly use another single quote to embed a PHP variable surounded by dots, hence the \' '. $PHP_VARIABLE .'\'

It's really obvious once you look at it this way. It took me weeks to find this solution, and it does not seem to be anywhere on the internet, as far as I know.

Here is another crazy JavaScript Gem:

onKeyup="var t=setTimeout(\'document.list.submit()\',0);"

[Again, note the back slashes because this is embedded within HTML embedded within PHP again, I just left all that out this time.] The setTimeout() to zero milliseconds before running the submit() method gets around a BUG in iPhone Safari Browsers which submits POST requests with the submit() method without capturing the contents of the text field. With the timeout function it somehow forces the BUGGY iPhone browser to submit the data in field with the POST.

No comments:

Post a Comment