Hi there,
I would like to know how I could implement JavaScript into a PHP file.
For example, I have a web page that informs the browser to select the javascript.php to be the JavaScript file.
From there, the code of that file is
<?php
echo "function validate_form() {
<!--
var username = document.getElementById(\\"username\\");
var password = document.getElementById(\\"password\\");
var status = document.getElementById(\\"status\\");
if (username.value.length <= 3) {
status.innerHTML = \\"Username is too short!\\";
username.focus();
return false;
}
else if (password.value.length <= 3) {
status.innerHTML = \\"Password is too short!\\";
password.focus();
return false;
}
else {
return true;
}
//-->
}";
?>
How can I use things like str_replace(“”, “”, variable); and whatnot in JavaScript?
Because, I tried using it with a JS variable, but it didn’t work… Any ideas?
Give this a shot:
<?php
echo " document.write('function validate_form() {');\
";
echo " document.write(' <!--');\
";
echo " document.write(' var username = document.getElementById(\\"username\\");');\
";
echo " document.write(' var password = document.getElementById(\\"password\\");');\
";
echo " document.write(' var status = document.getElementById(\\"status\\");');\
";
echo " document.write(' if (username.value.length <= 3) {');\
";
echo " document.write(' status.innerHTML = \\"Username is too short!\\";');\
";
echo " document.write(' username.focus();');\
";
echo " document.write(' return false;');\
";
echo " document.write(' } else if (password.value.length <= 3) {');\
";
echo " document.write(' status.innerHTML = \\"Password is too short!\\";');\
";
echo " document.write(' password.focus();');\
";
echo " document.write(' return false;');\
";
echo " document.write(' } else {');\
";
echo " document.write(' return true;');\
";
echo " document.write(' }');\
";
echo " document.write(' //-->');\
";
echo " document.write('}');\
";
?>
Remember, you must do this in your HTML:
<script type="text/javascript" src="phpscript.php"></script>
BTW, Here’s a javascript equivalent for str_replace:
JavaScript str_replace - php.js
put that in yor functions js file and you’ll be able to call it just like in php.
Not wishing to pour cold water, I would think carefully about dynamically generating JavaScript. Remember, JavaScript is Cached. It there any particular reason this file needs to be in a PHP file, and not just in a plain old javascript file?
There is no reason, really. I am new to JavaScript, and I was just curious if it were possible to a large extent. But I realize the answer now. So I require no more assistance, thanks. 