samedi 27 juin 2015

php ajax check if user exist

I am trying to see if the page title available for use. I'm trying to do this with normal function for availability of a user name. The problem that every time I get a title available although it already exists in a database. I am writing in Hebrew, all relevant pages are encoded UTF8. I do not know what to do, I'd love to help.

add_new_page.php:

<form role="form" data-toggle="validator" method="post" action="<?echo "$_SERVER[REQUEST_URI]";?>">
    <div class="form-group"><span id="frm_page_name_result"></span>
      <label for="frm_page_name"><?echo $lang['page_name']?>: <a data-toggle="modal" href="help/help_page_name.html" data-target="#HelpModal" class="glyphicon glyphicon-question-sign"></a></label>

     <input type="text" name="frm_page_name" id="frm_page_name" class="form-control" data-minlength="4" required />
    </div>

    <button type="submit" class="btn btn-success btn-lg" name="submit">אישור</button>
</form>

custom.js:

//check if page name exsist
$(document).ready(function() {

$("#frm_page_name").keyup(function (e) {

    //removes spaces from username
    //$(this).val($(this).val().replace(/\s/g, ''));

    var username = $(this).val();
    if(username.length < 2){$("#frm_page_name_result").html('');return;}

    if(username.length >= 2){
        $("#frm_page_name_result").html('<img src="images/ajax-loader.gif" />' );
        $.post('helpers/check_exists.php', {'username':username}, function(data) {
          $("#frm_page_name_result").html(data);
        });
    }
 });    
});

check_exists.php

<?php
###### db ##########
$db_username = '****';
$db_password = '****';
$db_name = '****';
$db_host = 'localhost';
 ################

 //check we have username post var
 if(isset($_POST["username"]))
 {
   $username=$_POST["username"];

   //check if its ajax request, exit script if its not
   if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND      strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    die();
 }

//try connect to db
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
$connecDB->set_charset("utf-8");
//trim and lowercase username
 $username =  strtolower(trim($_POST["username"])); 

//sanitize username
//$username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
//check username in db
$results = mysqli_query($connecDB,"SELECT * FROM pages WHERE page_name='$username'");

//return total count
$username_exist = mysqli_num_rows($results); //total records

//if value is more than 0, username is not available 
if($username_exist) {
    die('not-available');
}else{
    die('available');
}

//close db connection
mysqli_close($connecDB);
}

?>

Aucun commentaire:

Enregistrer un commentaire