php - Checking if username exists in Database jQuery -
i want check if username taken, here script, outputs "undefined". can me, please? :)
this in jquery - $("#registerusername").val() value of input.
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){ window.alert(data.exists); if(data.exists){ window.alert("name found"); }else{ window.alert("name not found"); } }, 'json');
this in checkregister.php
header('content-type: text/json'); if(!isset($_post['username'])) exit; $db = new pdo('mysql:host=localhost;dbname=testdatabase','root','pw000'); $query = $db->prepare("select * users username = '" . $_post['username'] . "'"); $query->execute(); echo json_encode(array('exists' => $query->rowcount() > 0));
first, might want strengthen php against sql injection 'sanitizing' input.
next why return json php? simpler return either true or false.
$db = new pdo('mysql:host=localhost;dbname=testdatabase','root','pw000'); $query = $db->prepare("select * users username = '" . $_post['username'] . "'"); $query->execute(); if( $query->rowcount() > 0 ){ echo 'true'; } else{ echo 'false'; }
then in javascript:
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){ window.alert(data); if(data == 'true'){ window.alert("name found"); }else{ window.alert("name not found"); } });
edit--- return boolean variable php rather string, either work
Comments
Post a Comment