disable button when username is taken jquery - javascript

I would like to be able to have my form disabled from submitting when username is taken, and I would like to get some help with that.
my js code is:
$('#username').keyup(function() {
var username = $(this).val();
$('#username_status').html('Searching...');
if (username !='') {
$.post('username_check.php', { username: username}, function(data) {
$('#username_status').html(data);
});
} else{
$('#username_status').html('');
}
});
and my for checking username exists or not:
<?php
if(isset($_POST["username"]))
{
define("HOST","localhost");
define("USERNAME","root");
define("PASS","");
define("DBNAME","testingproject");
$connecDB = mysqli_connect(HOST, USERNAME, PASS, DBNAME)or die('could not connect to database');
$username = $_POST["username"];
$results = mysqli_query($connecDB,"SELECT id FROM attendant WHERE username='$username'");
$username_exist = mysqli_num_rows($results); //records count
if($username_exist) {
$output= "Sorry, this Username is taken";
echo ($output);
}else{
echo('available');
}
}
?>

on php page
if($username_exist) { echo 'yes'; }
else { echo 'no'; }
on js,
$.post('username_check.php', { username: username}, function(data) {
if (data == 'yes') {
// here disable the registration button
} else {
// active the registration button
}
});
hope it help!
also you can check this thread: JQuery/Ajax Post returned data and IF function

Related

PHP code works when called with form action but not with ajax

The PHP code for login validation works properly when run from the html page by using form action but when run using ajax script it fails to load.
PHP code not involving database seems to run fine though.
JavaScript
< script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > < /script> <
script >
$(document).ready(function() {
$("#login").submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var postForm = { //Fetch form data
'name': $('input[name=name]').val(),
'password': $('input[name=password]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type: 'POST', //Method type
url: '.php', //Your form processing file url
data: postForm, //Forms name
dataType: 'json',
success: function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name).append('<p>' + data.error + '</p>'); //Throw relevant error
alert("Nope");
}
} else {
$('#success').fadeIn(1000).append('<p>' + data.name + '</p>'); //If successful, than throw a success message
alert("yes");
}
}
});
event.preventDefault(); //Prevent the default submit
});
}); < /script>
PHP Code
<?php
$errors = array();
$form_data = array();
include("config.php");
if (session_status() == PHP_SESSION_NONE) {
session_start();}
else{
$_SESSION['ses']="Already in session":
/* Write already in session code */
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT * FROM users WHERE user_name = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}
if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
else{
if($count == 1) {
$_SESSION['login_user'] = $myusername;
}else {
$error = "Your Login Name or Password is invalid";
$_SESSION["error"] = $error;
}
}
}
echo json_encode($form_data);
?>

session not regestring the 3 variable

I have created a login system in codeigniter. It's working fine, but when i login it registers only 2 variable which are login and password but not showing me the 3rd variable in the session which is user_type. I have tried too much but i can not understand what is wrong.
model code
function login($username, $password) {
//create query to connect user login database
$this->db->select('user_id, username, password','user_type');
$this->db->from('login');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status',1);
$this->db->limit(1);
//get query and processing
echo $query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result(); //if data is true
} else {
return false; //if data is wrong
}
}
varifying code controller
function index() {
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE) {
$this->load->view('v_login');
} else {
//Go to private area
redirect(base_url('c_home'), 'refresh');
}
}
function check_database($password) {
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->login->login($username, $password);
if($result) {
$sess_array = array();
foreach($result as $row) {
//create the session
$sess_array = array('user_id' => $row->user_id,
'username' => $row->username,
'user_type'=> $row->user_type
);
//set session with value from database
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
} else {
//if form validate false
$this->form_validation->set_message('check_database', '<p style="color: red;">اسم المستخدم / كلمة المرور غير صحيحة ! </p>');
return FALSE;
}
}
session variable code
function session_start(){
/*---------------------------- session start here */
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data['id'] = $session_data['user_id'];
$data['user_type'] = $session_data['user_type'];
} else {
//If no session, redirect to login page
redirect('c_login', 'refresh');
}
/* ---------------------- session start ends */
Because you are not selecting user_type in your select query.
Change this :
$this->db->select('user_id, username, password','user_type');
With this :
$this->db->select('user_id, username, password,user_type');

"\r\n\" in alert for jquery ajax html

I have an ajax request that looks like this
$(document).ready(function() {
$(document).on('click', '#submit', function() {
var UserName = $('#username').val();
var PassWord = $('#password').val();
console.log(UserName);
$.ajax({
type: 'POST',
url: 'ajax/Login.php',
dataType: "text",
data: {
username: UserName,
password: PassWord
},
success: function(data) {
alert(JSON.stringify(data));
window.location='pages/mainpage.php';
},
error: function(data) {
alert('Login Error');
//window.location='../index.php';
}
});
});
});
and my php is like this
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
echo "Welcome ".$username;
}else{
echo "Password incorrect";
}
}
}else{
echo "Username is empty";
}
When i dont put anything in username i am expecting that the alert will be Username is empty same as when password is empty alert should be Password incorrect but i am getting "\r\n\" but if put some in username like John it will alert Welcome John"\r\n\" why is this happening?how to make it alert Username is empty when username is empty same with password?any idea is accepted..
Try this: in ajax section, dataType: "text", change to dataType: "json", and server php code is following: it may work
//put this function top of this page
ob_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$json="";
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
$json.="Welcome ".$username;
}else{
$json.="Password incorrect";
}
}
}else{
$json.="Username is empty";
}
ob_end_clean();
echo json_encode($json);
?>
I change isset to !empty fixed the problem

Using Ajax code to display a popup message when data get inserted in to the database

When submitting my form I need to check in the database whether chassis and pin exists. If it exists i need to display a pop up message through Ajax. This is my code. But i am not getting any pop up message if the data has been inserted or if there is any error.Can you guys help me figure out where I am going wrong? Thanks in advance for your help.
AJAX CODE :
<script type="text/javascript">
$(document).ready(function () {
$("#user_submit_form").submit(function () {
var user_data = $("#user_submit_form").serialize();
if ($('#chassis').val() == '') {
alert('Please enter chassis');
} else if ($('#pin').val() == '') {
alert('Please enter pin');
} else
{
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success: function (user_data) {
if (user_data == "Data inserted") {
alert("Data inserted");
} else {
alert("fail!");
}
}
}); // End ajax method
}
});
});
</script>
PHP CODE:
<?php
session_start();
$hostname = '*****';
$database = '****';
$username = '****';
$password = '*****';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
die("Unable to Connect server!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT chassis,pin FROM checking_chassis WHERE chassis="'.$chassis.'" && pin="'.$pin.'" ');
if(mysql_num_rows($sql) == 1)
{
echo "Data inserted";
}
else
{
echo "Error";
}
?>
first do this after submitting and check
$("#user_submit_form").submit(function(e){
e.preventDefault();
});
and when alerting return false;
OR
pass data like this
$data = array(
'status' => 1,
'message' => 'Data inserted'
);
echo json_encode($data);
and in success function use
var json = $.parseJSON(user_data);
alert(json.message);
I am trying this now but I don't think that the value is getting returned. It is just printing the content of the else statement
<script type="text/javascript">
$(document).ready(function (){
$("#user_submit_form").submit(function(){
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
var pincode = new Array();
pincode = $('#pincode').val().split("");
if($('#chassis').val() =='')
{
alert('Please enter chassis');
}
else if($('#pin').val() =='')
{
alert('Please enter pin');
}
else
{
$.post("validate_user.php",{"chassis":$('#chassis').val(),"pin":$('#pin').val(),"title":$('#title').val(),"fname":$('#fname').val(),"lname":$('#lname').val(),"email":$('#email').val(),"mobile":$('#mobile').val(),"dob":$('#dob').val(),"anniversary":$('#anniversary').val(),"company":$('#company').val(),"designation":$('#designation').val(),"home_business":$('#style').val(),"add1":$('#add1').val(),"add2":$('#add2').val(),"city":$('#city').val(),"state":$('#state').val(),"pincode":$('#pincode').val()},function(data) {
if(data == true)
{
alert("Error");
}
else
{
alert("Success");
}
});
}
});
});
</script>

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Categories

Resources