I Need to initialise PHP variable inside the javascript function?
The above code is an javascript function . I need to initialise PHP variable in the else part
function validate() {
if(document.loginForm.vuser_login.value==""){
alert("Login Name name cannot be empty");
document.loginForm.vuser_login.focus();
return false;
} else if (document.loginForm.vuser_password.value=="") {
alert("Password cannot be empty");
document.loginForm.vuser_password.focus();
return false;
} else {
//Here i need to initialise PHP variable ......
ret开发者_高级运维urn true;
}
}
I think you have a fundamental misunderstanding in how PHP and Javascript work. PHP runs before Javascript, on the server. Javascript is interpreted after the page has been delivered, in the browser.
Depending on what you want to do, you may want to use AJAX. Impossible to tell for sure from the data.
Agree with what @Pekka is saying.
The only way to do it is to generate the JS from PHP
<? php
$yourVar = 'abc';
echo "
function validate() {
if(document.loginForm.vuser_login.value==\"\"){
alert(\"Login Name name cannot be empty\");
document.loginForm.vuser_login.focus();
return false;
} else if (document.loginForm.vuser_password.value==\"\") {
alert(\"Password cannot be empty\");
document.loginForm.vuser_password.focus();
return false;
} else {
var = '" . $yourVar . "';
return true;
}
}
";
By the time that else if
condition has been met, PHP is out of the picture.
you can add new variable with the PHP tags in between javascript.
var phpvar = <?PHP $var1 ?>;
The javascript code runs on the client (browser) and it of course can't access a php variable, which only exists server-side. The only thing you can do is to use an Ajax call, which will call a php service. I don't think however that this is what you are after for.
精彩评论