简体   繁体   中英

Can't use PHP inside script tag

I'm using JavaScript to alert out an error

If a user's input wrong and I put the code below:

<?php $_POST["usernamereg"] ?> = usernamereg;

the script won't alert anymore. If I remove it, then it can alert again.

<script type="text/javascript">

var usernamereg;
var passwordreg;
var password2reg;
const regisForm =document.getElementById("reg-form");
function getValue(){
 usernamereg = document.getElementById("usernamereg").value;
passwordreg = document.getElementById("passreg").value;
password2reg = document.getElementById("pass2reg").value;
}
regisForm.addEventListener("submit", (e) => { 
e.preventDefault();
getValue();


    if (usernamereg.length > 30 || usernamereg.length < 5){
        alert("Your username must be longer than 5 and less than 30"); 
        <?php $err = 1;?>;
    }else { 

        <?php $_POST["usernamereg"] ?> = usernamereg;
        <?php $err = 0;?>
    }

    if (passwordreg.length > 30 || passwordreg.length < 8){
        alert("Your password must be longer than 8 and less than 30"); 

        <?php $err = 1;?>
    } else {

          <?php $_POST["passreg"] ?> = passwordreg;

        <?php $err = 0;?>
    }
    if (password2reg!=passwordreg){
        alert("Your re-type password doesnt match");
        <?php $err = 1;?>
    }else {
          <?php $_POST["pass2reg"] ?> = password2reg;

        <?php $err = 0;?>
    }

});
</script>  

You need to echo the value or you are trying to set nothing to the value of password2reg .

<?php echo $_POST["passreg"] ?> = passwordreg;

Note that this is likely not a great pattern as it is very error prone.

The code which you have written

<?php $_POST["usernamereg"] ?> = usernamereg;

you are trying to assign a javascript variable to PHP post variable.

This is not correct.

It would be better you could post your html form code because you don't need to set the $_POST["usernamereg"] because its already set when you submit the form.

If your username and password are correct then you just need to submit the form.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM