最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

I Need to initialise PHP variable inside the javascript function? - Stack Overflow

programmeradmin0浏览0评论

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 ......
        return true;
    }
}

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 ......
        return true;
    }
}
Share Improve this question edited Dec 7, 2010 at 11:15 bcosca 17.6k5 gold badges42 silver badges51 bronze badges asked Dec 7, 2010 at 10:44 Prajwal GNPrajwal GN 112 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 8

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.

发布评论

评论列表(0)

  1. 暂无评论