AJAX username Availability - php

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.

Related

Javascript, Php, Ajax

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.

Checking if username exists in Database jQuery

I want to check if the username is already taken, here is my script, which outputs "undefined". Can anyone help me, please? :)
This is in my jQuery - $("#registerusername").val() is the value of an input.
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data.exists);
if(data.exists){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
}, 'JSON');
This is in my 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 * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
echo json_encode(array('exists' => $query->rowCount() > 0));
First, You might want to strengthen your php against sql injection by 'sanitizing' the input.
Next why return JSON from the php? It would be much simpler to just return either true or false.
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
if( $query->rowCount() > 0 ){
echo 'true';
}
else{
echo 'false';
}
Then in your javascript:
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data);
if(data == 'true'){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
});
edit---
You could also just return a boolean variable from php rather than a string, but either will work
Simple Example..
Jquery
var username = $.trim($('#username').val());
if(username != '') {
$.ajax({
url : 'localhost/phpScript.php',
data : {username : username},
dataType : 'JSON',
type : 'POST',
cache : false,
success : function(result) {
if(result == '1') { alert('Username Found.'); }
else if(result == '0') { alert('Username Not Found!'); }
},
error : function(err) {
console.log(err);
}
});
}
PHP/MySQL (Make sure that you escape value for user input, Before giving it to MySql)
if(isset($_POST['username'])) {
$username = $_POST['username'];
$sql = "SELECT username FROM users WHERE username = '".$username."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == '1') {
echo '1';
} else {
echo '0';
}
}

Ajax post success function returning both success and error

Okay so I am trying to get ajax to post to my php file, lookup a mysql field and if it exists echo 'clientsuccess' otherwise echo 'Client already exists'
but on success function it returns both values despite the fact that they're in an php if statement.
I am quite possibly missing something incredibly simply, but any help is greatly appreciated.
PHP:
<?php
session_start();
$clientArray = $_POST['clientArray'];
$clientArray = explode(',', $clientArray);
$count = 0;
foreach($clientArray as $clientField)
{
trim($clientField);
if(empty($clientField)) {
$clientField = '-';
}
}
$con = mysql_connect("localhost",$_SESSION['MysqlUser'],$_SESSION['MysqlPass']);
if (!$con)
{
die('Could not connect with '.$_SESSION['MysqlUser'].mysql_error());
}
mysql_select_db("smeinsti_SPW_Inventory", $con);
$checkclient = mysql_query("SELECT ClientName FROM Clients WHERE ClientName = '".$clientArray[0]."'", $con);
if(mysql_num_rows($checkclient)==0)
{
$sql="INSERT INTO Clients (`ClientName`, `PhoneNumber`, `Email`, `Address`, `OrderDate`)
VALUES
('$clientArray[0]', '$clientArray[1]', '$clientArray[2]', '$clientArray[3]', CURDATE())";
$clientArray[0] = $_SESSION['ClientName'];
echo "clientsuccess";
} else {
echo 'Client already exists';
}
?>
JS:
function NextPage()
{
var ClientData = [];
$('form#order-form.create input[type=text]').each(function() {
ClientData += $(this).val() + ',';
})
alert(ClientData);
var parameters = {
clientArray: ClientData
};
$.ajax({
type: "POST",
async:false,
url: "write_client.php",
data: parameters,
success: function(result){
var res=result;
if(res = 'clientsuccess') {
window.location = 'admin.php?id=7';
} else {
alert('Client already exists');
}
}
});
}
Your condition Equal symbol is not correct! Put '=='
if(res == 'clientsuccess') { //Double Equal to
window.location = 'admin.php?id=7';
} else {
alert('Client already exists');
}
mysql_num_rows returns the number of selected rows and not the fields of a certain row. Use mysql_fetch_row to fetch the row you have selected with your query:
You could also use mysql_result to fetch a row and get a certain field:
$client exist = mysql_result($checkclient, 0, 0);
This fetches the first row (zero based) and returns the first field (zero based).

Populating span/div with database record

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);
}
}

JQuery/Ajax calling function incorrectly

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.

Categories