简体   繁体   中英

Send two variables from php to javascript

I want to send two variables from the php file to the javascript. I've set this up:

Javascript code

<script>
function cek(user,pass){
    alert("a");
    alert(user);
    alert(pass);


    if(pass!=pass1){
        alert('Password Anda Salah');
    } else if(user==user1){
        alert('Username baru sama dengan username lama');
    }


}
</script>

PHP code

<?php
    include "db.php";
    $nip=$_REQUEST['nip'];

    $query=mysql_query("SELECT username,password FROM user WHERE nip=$nip",$koneksi);
    $row=mysql_fetch_array($query);
    $username=$row['username'];
    $password=$row['password'];
    echo'<font face="verdana" size="3" color="black"><br />';

    echo'<form method="post" name="form1">';

    echo'<label>Username </label>&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp;';

    echo"<input type='text' id='user' name='user' tabindex='1' value=$username> <br />";

    echo'<label>Username Baru</label> &nbsp; &nbsp; &nbsp;';

    echo'<input type= "text" id="user1" name="user1" tabindex="2"/> <br />';

    echo'<label>Password</label> &nbsp;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;';

    echo'<input type="text" id="pass" name="pass" tabindex="3" value=$password> <br />';

    echo"<button type='button' name='submit' id='submit' onclick=subtotal(".$username.",\"".$password."\"))>Submit</button>";
    echo'</form>';
    echo'</font>';
?>

I've tried to do it this way. But it does not work properly, please help me or give some advice to solve this problem.

you can try this : in php :

 <div id="myid" data-var1="<?php echo $var1;?>"  data-var2="<?php echo $var2;?>">    </div>

in jquery :

  var var1=$('#myid').attr('data-var1');
  var var2=$('#myid').attr('data-var2');

and you can use this variables in javascript function

var user = $('#user').val();
var pass = $('#pass').val();
function cek(user,pass) {
 // your script here
}

To send a variable from PHP to JavaScript , You can set the PHP variable to JavaScript variable and the JavaScript variable will be available on your script.

PHP:

$php_var1='Var_1_Value';
$php_var2='Var_2_Value';

echo "<script>";
echo "var js_var_1 = $php_var1"; //double quote So PHP variable will work in string
echo "var js_var_2 = $php_var2"; 
echo "</script>";

Now js_var_1 and js_var_2 will be available on your scope and can use:

<script>
    alert(js_var_1);
    alert(js_var_2);
</script>

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