0

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

7
  • When is input.data.js initialized? Commented Feb 1, 2015 at 13:10
  • just show us what is you html gererated is <script language="javascript" type="text/javascript"> var nick_exist = ""; </script> ??? Commented Feb 1, 2015 at 13:10
  • 3
    make the php file to print 'true' or 'false', and use the printed to make the $.post inside condition $.post('data.check.php', {nick: v_nick} ,function(response) { alert(response); } Commented Feb 1, 2015 at 13:11
  • 1
    I agree with @Yair.R you even don't need that <script language="javascript" type="text/javascript"> var nick_exist = "<?php echo $nick_exist; ?>"; </script> just echo $nick_exist; to the stream. and check response on javascript side Commented Feb 1, 2015 at 13:14
  • use can print a json in data.check.php page and get json by jquery .ajax Commented Feb 1, 2015 at 13:18

1 Answer 1

1

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!');
    }
});
Sign up to request clarification or add additional context in comments.

8 Comments

$nick_exist will return a number in the php, so the JS condition you have posted is wrong :)
if(parseInt(resp.count) > 0)
it is integer value already so no need to check on front-end.
But you must check if its bigger than 0, or it will always return true
0 means false any non 0 is true value.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.