Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
jQuery PHP: Check if username already exist

I'm trying to check the existence of an username already registered on my application using jQuery+Ajax+POST.

HTML

<div class="form-group">
    <label for="username" class="col-md-3 control-label">Username</label>
    <div class="col-md-9">
        <input type="text" id="username" class="form-control" name="username" placeholder="Username">
    </div>
</div>
<div class="col-sm-9 col-sm-offset-3" id="userCheck">
    <div class="alert alert-info" id="userCheckLabel"></div>
</div>

jQuery

$('#username').focusout(function() {
    var username = $('#username').val();
    checkUserExist(username);
})
function checkUserExist($uname) {
    $.post( "../core/lib/checkUserExist.php", function( data ) {
    if(data.html == 'true') {
       $('#userCheck').slideDown("slow");
       $('#userCheckLabel').text("This user already exist!")
    }
});

PHP

<?php
require_once('../../core/class.user.php');
$user = new USER();
$uname = $_POST['username'];

$stmt = $user->runQuery("SELECT user_nameFROM users WHERE user_name=:uname ");
$stmt->execute(array(':uname'=>$uname));
$row=$stmt->fetch(PDO::FETCH_ASSOC);

if($row['user_name']==$uname) {
    print 'true';
} else {
    print 'false';
}
?>

I Don't include class.user.php cause It's only handling the PDO Connection, If I remove the if(data.html == 'true') the connection work as expected and the message come out.

Behavior

The code work if I remove the if(data.html == 'true'). but with this it doesn't do anything, no errors in console. So I think the error is in the way I handle the PHP part. Any suggestion?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Since you are returning string not HTML, so you have to do like below:-

$.post( "../core/lib/checkUserExist.php",{username: uname }, function( data ) {
     console.log(data);// check this and let me know the output
     if(data == 'true') {  // or try if(data)
       $('#userCheck').slideDown("slow");
       $('#userCheckLabel').text("This user already exist!")
    }
});
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!