I'm creating a system that checks (via AJAX) if a given username is already taken. If so, then it alerts the user accordingly. I'm basing my system off of this tutorial and have tried adapting it to my site.
$(document).ready(function()//When the dom is ready
{
$("#username").change(function()
{ //if theres a change in the username textbox
var username = $("#username").val();//Get the value in the username textbox
if(username.length > 3)//if the lenght greater than 3 characters
{
$("#availability_status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
//Add a loading image in the span id="availability_status"
$.ajax({ //Make the Ajax Request
type: "POST",
url: "ajax_check_username.php", //file name
data: "username="+ username, //data
success: function(server_response){
$("#availability_status").ajaxComplete(function(event, request){
if(server_response == '0')//if ajax_check_username.php return value "0"
{
$("#availability_status").html('<img src="available.png" align="absmiddle"> <font color="Green"> Available </font> ');
//add this image to the span with id "availability_status"
}
else if(server_response == '1')//if it returns "1"
{
$("#availability_status").html('<img src="not_available.png" align="absmiddle"> <font color="red">Not Available </font>');
}
});
}
});
}
else
{
$("#availability_status").html('<font color="#cc0000">Username too short</font>');
//if in case the username is less than or equal 3 characters only
}
return false;
});
});
ajax_check_username.php - HERE's where I think I'm having problems!!
<?php
include ("inc/db/db.php");
if($stmt = $mysqli->prepare('SELECT NULL FROM `bruger` WHERE `brugernavn` = ?'))
{
$stmt->bind_param('s', $brugernavn);
$brugernavn = $_POST["brugernavn"];
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if($count = 0)
{
echo '1';
}
else
{
echo '2';
}
}
?>
<tr>
<td><p>Brugernavn</p></td>
<td><input type="text" name="brugernavn" id="username"></td>
<td><span id="availability_status"></span></td>
</tr>
ATTENTION
I think I've made mistakes in my php, so it may be why it does not bother to do what I want it .. but it's just when I think.
This is what my html looking for when I need to check user name in the database. this is how I get no errors at all. it must be said that I never play with ajax or javascript before. so it will be a great help if you could help me further.
Feel free to ask if there is more you want to know something.
This if($count = 0) should be if($count == 0) if that affects your logic.
You're assigning $brugernavn after you're using it.
$stmt->bind_param('s', $brugernavn);
$brugernavn = $_POST["brugernavn"];
Using ajaxComplete is not useful here:
$("#availability_status").ajaxComplete(function(event, request){
You are assigning where you should be comparing:
if($count = 0)
Your Javascript expects a 0 or 1, but your PHP script outputs one of 1 or 2.
Related
I have a problem with this my script.
$("#login").click(function(event) {
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "1"){
alert(data);
}
}
})
I want it to alert a value that I am getting from an echo in another php file
<?php
if(isset($_POST['userLogin'])){
$email = mysqli_real_escape_string($con, $_POST['userEmail']);
$password = md5($_POST['userPassword']);
$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";
$query_login = mysqli_query($con, $sql_login);
$count_login = mysqli_num_rows($query_login);
if($count_login == 1){
$row_login = mysqli_fetch_assoc($query_login);
$_SESSION['uid'] = $row_login['user_id'];
$_SESSION['name'] = $row_login['first_name'];
echo "1";
}
}
?>
If I didn't put the alert(data) in an if condition, it displays the value I echo, but I need the condition to enable the right user logged in.
What can IF can also ELSE.
In your ajax add the else conditions to see if it helps uncover the issue:
if (data == "1") {
alert('youre in');
} else {
alert('try again');
}
And in your php, also account for the else condition (and do strict checking on that count of rows with ===):
if ($count_login === 1) {
// code ...
echo '1';
} else {
echo 'Sorry, the login is incorrect';
}
It works fine for me, if i always echo "1", the alert(data) show 1, in an if condition and out, pls, echo something else if isset($_POST['userLogin']) or $count_login == 1 are false, or put an
error : function(data) {
$('body').append("<div>"+data.responseText+"</div>")
}
in your ajax, to debug the prob. Because in your .php file, when you echo nothing, it returns a data in error, not in success, maybe that's your prob.
I have a problem and a question for the code below.
The code below performs a live check if username already exists in database. Now when I enter username manually it all works fine with giving live success or error message as the case is but when after typing 1 or 2 characters I choose username from autofill options given by browser It doesn't give any success or error message instead keeps showing Enter 3 to 11 characters which is initial message for username requirements. Can't figure out why it doesn't work when username is selected from autofill options.
index.php
<script type="text/javascript">
$(document).ready(function(){
$('#un').keyup(function(){
var username = $(this).val();
var Result = $('#result');
if(username.length > 2 || username.length > 11) { // if greater than 2 (minimum 3)
Result.html('./img/loadgreen.gif');
var dataPass = 'action=availability&username='+username;
$.ajax({ // Send the username val to available.php
type : 'POST',
data : dataPass,
url : 'available.php',
success: function(responseText){ // Get the result
if(responseText == 0){
Result.html('<span class="success">Available</span>');
}
else if(responseText > 0){
Result.html('<span class="error">Unavailable</span>');
}
else{
alert('Problem with sql query');
}
}
});
}else{
Result.html('Enter 3 to 11 characters');
}
if(username.length == 0) {
Result.html('');
}
});
});
</script>
<table>
<tr>
<td>
<input type="text" name="username" id="un" placeholder="Username" class="username" />
</td>
<td class="result" id="result"></td>
</tr>
</table>
available.php
<?php
include ( "./inc/connect.php" );
if(isset($_POST['action']) && $_POST['action'] == 'availability')
{
$username = $_POST['username'];
$que=$db->prepare("SELECT username FROM users WHERE username=:username");
$que->execute(array(':username'=>$username));
$count = $que->rowCount();
echo $count;
}
?>
Now my question is how to secure POST on available.php lot of people tell you need to sanitize or escape every POST and GET data. So what works best with PDO. Also heard escaping doesn't works with PDO may be I am wrong?
try jquery .change() instead of .keyup()
I have writtin this code to check the email availability.
var email = $('#email_reg').val();
if(email && email.length > 0)
{
if(!isValidEmailAddress(email))
{
isValid = false;
$('#msg_email').html('Email is invalid').show();
}
else
{jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'email='+ email ,
cache: false,
success: function(response){
if(response == 1){
$('#msg_email').html('Email already Exists').show();
isValid=false;
}
else {
$('#msg_email').html('').hide();
}
}
});
}
}
else
{
isValid = false;
$('#msg_email').html('Please enter email').show();
}
The php Code is
<?php
require_once('Connections/connection.php');
$username= mysql_real_escape_string($_REQUEST["email"]);
if (!$con)
{
echo 0;
}
else {
mysql_select_db($database_connection, $connection);
$result = mysql_query("SELECT * FROM vendor_logiin WHERE username='" . $username . "'");
$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();
?>
Now all the others work well like when left it empty and give a wrong email format.But the problem is when i give an email Id that already exists. It didnot give error.
I have no idea what is going wrong.
Since you didn't specify dataType the response is probably treated as text or html and in that case it might be wise to do the comparison as a string:
if (response == "1") {...}
instead of a number. Or use parseInt(response, 10) == 1 if you compare it as a number.
I apologise if this comes across as really stupid. I have searched but can't seem to find an answer. I hope I can explain what it is I am trying to do.
I want to be able to query a database and if there is a record in it to show the record in the span/div or show a not found error message if there isn't.
I have a jquery check up and running to check if a username is in the database, what I want to know is how easy it would be to ammend this to pull all the data and show it in the span/div on the original page.
This is the jquery I have:
$(document).ready(function () {
$('#username').keyup(username_check);
});
function username_check() {
var username = $('#username').val();
if (username == "" || username.length < 2) {
$('#username').css('border', '1px #D5D5D5');
$('#cross').hide();
$('#tick').hide();
} else {
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function (response) {
if (response == 1) {
$('#username').css('border', '2px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '2px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
Can I do all this on the one page and query the db from the same page, instead of posting it to another page as I don't know how to get the results back to the calling page?
I hope I have explained what I want to do. Apologies if I haven't
Here is the PHP code:
$username = trim(strtolower($_POST['username'])); $username = mysql_escape_string($username); $query = "SELECT adbkid FROM person WHERE adbkid = '$username' LIMIT 1"; $result = mysql_query($query); $num = mysql_num_rows($result); echo $num; mysql_close()
You will normally send ajax requests to pages hosted on your server. So you can't directly access your database without going through your server. You'll need to write a function on your server that queries the database, and then call that function from javascript using ajax.
You can output a string in PHP and then set that text value to an element with jQuery ( $('#element').val(responseFromServer);
or $('#element').html(responseFromServer);
Instead of sending back "1" send back a json response something like:
/* record exists */
{status:1, html:'server generated message about record'}
/* doesn't exist */
{status:0}
This will allow you to still change css based on response data status value
Can use $.post ajax shorthand method:
$.post('check.php',{username: username}, function(response){
var upDateElement=$('#spanID');
if(response.status && response.status== 1){
$('#username').css('border', '2px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
upDateElement.html( response.html)
}else{
$('#username').css('border', '2px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
upDateElement.html('Message html for no record found')
}
},'json')
check.php
$data = array();
$data['exists'] = false;
if(!isset($_POST['username'])) {
echo json_encode($data);
exit();
}
$username = mysql_escape_string($_POST['username']);
$query = "SELECT adbkid FROM person WHERE adbkid = '$username' LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if(count($row) == 1) {
$data = $row;
$data['exists'] = true;
}
return json_encode($data);
from your jQuery:
success: function(response) {
/**
* For instance, for a table with id, username, password and email you have
* data.exists = true/false;
* data.id = 1;
* data.username = 'foo';
* data.password = 'sample data password';
* data.email = 'foo#bar.com';
*/
if(response.exists === true) {
$('#username').val(response.username);
$('#email').val(response.email);
}
}
Summary: This is a basic, stand alone web form. Just html form, with a JQuery included for the functions.
I have a form that checks email and username for uniqueness and validity (of email). I'm using a JQuery onChange event to call each function, which is an Ajax call to a php file.
The JQuery for the username check is as follows:
$("#username").change(function() {
var username = $("#username").val();
var msgbox_username = $("#username_status");
var dataString = "username="+ username;
$("#username_status").html('<img src="images/loader.gif">Checking Availability.');
if (username != "" && username.length >= 6){
$.ajax({
Type: "POST",
url: "functions/check_username.php",
data: dataString,
success: function(msg_username) {
$("#username_status").ajaxComplete(function (event, request) {
if (msg_username == 'Username Ok') {
$("#username").removeClass("red").addClass("green");
msgbox_username.html('<font color="Green">Available</font>');
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html(msg_username);
}
});
}
});
return false;
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html('<font color="Red">Username of 6 or more characters is required</font>');
}
});
The check_username.php file is as follows:
<?php
$username = $_GET["username"];
include_once("../includes/connect.php");
$query = "SELECT username
FROM sss_users
WHERE username = '$username'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0 && strlen($username) >= 6) {
echo '<font color="#cc0000"><strong>' . $username . '</strong> is already in use. </font>';
} else {
echo 'Username Ok';
}
?>
Continuing with the pattern, the email JQuery:
$("#email").change(function() {
var email = $("#email").val();
var msgbox_email = $("#email_status");
var dataString = "email="+ email;
$("#email_status").html('<img src="images/loader.gif">Checking Availability.');
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length){
$("#email").removeClass("green").addClass("red");
msgbox_email.html('<font color="Red">Valid Email Required</font>');
} else {
$.ajax({
Type: "POST",
url: "functions/check_email.php",
data: dataString,
success: function(msg_email) {
$("#email_status").ajaxComplete(function (event, request) {
if (msg_email == 'Email Ok') {
$("#email").removeClass("red").addClass("green");
msgbox_email.html('<font color="Green">Available</font>');
} else {
$("#email").removeClass("green").addClass("red");
msgbox_email.html(msg_email);
}
});
}
});
return false;
}
});
And the email PHP:
<?php
$email = $_GET["email"];
include_once("../includes/connect.php");
$query = "SELECT email
FROM sss_users
WHERE email = '$email'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0) {
echo '<font color="#cc0000"><strong>' . $email . '</strong> is already in use. </font>';
} else {
echo 'Email Ok';
}
?>
They each work seperately, but if I put an invalid username in the box and then put a valid email, somehow the check_username.php file is called and no matter what is in the box (valid or not) it thinks it's a valid username.
An example is:
All functions are called on the OnChange Event
1) type in the username asdfasdf (which is available)
2) Delete the username asdfasdf from the text box (this works correctly, displaying a username must have at least 6 characters)
3) type in any valid email
Result: the valid email works correctly, but the username field (which is blank) recalls what was there before (asdfasdf) and says it is a valid username (even though the field is still blank.)
Hope this makes sense. Any suggestions?
SOLUTION
As noted below, the .ajaxComplete() was calling all functions with that tag. Therefore, when I made the following changes it worked:
$("#username_status").ajaxComplete(function (event, request) { ... code here ... });
changed to:
$("#username_status").ajaxComplete(function (event, request, settings) { ... code and new if statement ... });
And then I wrapped
if(settings.url == 'functions/check_username.php') {}
around the validation code. This process was done for both the username and email validation.
http://api.jquery.com/ajaxComplete/
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
Maybe both handlers are being fired.