简体   繁体   中英

Javascript cant get value from PHP variable?

I want make data exist checker. data.check.php:

<?php
    $nick   = mysql_real_escape_string($_POST['nick']);
    $query = mysql_query("select * from tb_user WHERE nick='$nick'");
    $nick_exist = mysql_num_rows($query);
?>

<script language="javascript" type="text/javascript">
    var nick_exist = "<?php echo $nick_exist; ?>";
</script>

and this for $POST data input.data.js

var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function() {
    if(nick_exist){
        window.alert('Choose another nick please!');
    }
});

I dont know where is the problem and my windows.alert is not running :(

thanks u

try like this get the count in php then return it to js:

NOTE: Please do not use mysql it is deprecated now start using mysqli or pdo .

data.check.php:

<?php
    $nick   = mysql_real_escape_string($_POST['nick']);
    $query = mysql_query("select * from tb_user WHERE nick='$nick'");
    $nick_exist = mysql_num_rows($query);
    echo json_encode(array('count'=> $nick_exist));//send result to javascript
?>

input.data.js

var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function(resp) {
var resp=JSON.parse(resp);
    if(resp.count){
        window.alert('Choose another nick please!');
    }
});

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