I need an AJAX Login Script for my school project.
But it actually won't work because when I try to login, I get kicked to the startpage (login-form) without any message.
That's my backend-script (login2.php):
if(empty($_POST['loginEmail']) || empty($_POST['loginPassword'])) {
$error[] = "Bitte füllen Sie alle Felder aus!";
}
if (!empty($_POST['loginEmail']) && !filter_var($_POST['loginEmail'], FILTER_VALIDATE_EMAIL)) {
$error[] = "Bitte geben Sie eine gültige E-Mail-Adresse an!";
}
if(count($error)>0) {
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email AND `uPassword` = :password";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $_POST['loginEmail']));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($row)>0) {
if(!password_verify($_POST['loginPassword'],$row[0]['uPassword'])) {
$error[] = "Falsches Passwort!";
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
session_start();
$_SESSION['Email'] = $row[0]['uEmail'];
$resp['redirect'] = "dashboard.php";
$resp['status'] = true;
echo json_encode($resp);
exit;
}
else {
$error[] = "Falsche E-Mail-Adresse!";
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
And this is my JS part of the login form:
$(function() {
$('#login').click(function(e){
let self = $(this);
e.preventDefault();
self.prop('disabled',true);
var data = $('#login-form').serialize();
$.ajax({
url: '/login2.php',
type: "POST",
data: data,
}).done(function(res) {
res = JSON.parse(res);
if(res['status']) {
location.href = "dashboard.php";
} else {
var errorMessage = "";
console.log(res.msg);
$.each(res['msg'],function(index,message) {
errorMessage += '<p>' + message + '</p>';
});
$("#error-msg").html(errorMessage);
$("#error-msg").show();
self.prop('disabled',false);
}
}).fail(function() {
alert("error");
}).always(function(){
self.prop('disabled',false);
});
});
});
When I try to add action="/login2.php" in the form I get a HTTP 500 Error and the message, that it can not process this request at this time.
I'm not sure if this is your main problem, but it's a significant one. You're preparing two parameters:
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email AND `uPassword` = :password";
But you're only binding one:
$stmt->execute(array(':email' => $_POST['loginEmail']));
You don't want to include the password in the select, since you're using password_verify() to validate it later. Change your SQL to this:
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email";
Related
So I've got my password being passed to a php page and returning json data
However if it returns nothing. nothing happings. My Failed login never fires. Can someone tell what I'm doing wrong.
<script>
$(document).ready(function(){
var password = "";
//PRESSING AN INPUT KEY
$('.sixPinInput').keyup(function (k) {
if (this.value.length == this.maxLength) {
password = password+this.value;
password = password.substring(0,6);
$(this).next('.sixPinInput').focus();
$(".pinIncorrectMessage").css("display", "block");
$(".pinIncorrectMessage").html(password);
}
//PRESSING DELETE
if (k.keyCode == 8) {
$(this).prev().val("").focus();
password = password.slice(0, -1);
$(".pinIncorrectMessage").html(password);
}
});
//PRESSING LAST INPUT KEY
$("#f").keyup(function() {
if($("#f").val().length > 0) {
$.post("http://heber/QC/includes/getUserInfo.php", {user: password}, function(data, status) {
//IF SUCCESSFUL LOGIN
password = "";
$(".sixPinInput").val("");
if(data) {
$(data).each(function(index, value) {
alert(value.firstName + value.lastName)
$(".cover").fadeOut(200);
$(".sixPinInputContainer").fadeOut(200);
$("#pageBody").css("overflow", "scroll");
})
}
//IF FAILED LOGIN
if(!data) {
$(".cover").fadeOut(200);
$(".sixPinInputContainer").fadeOut(200);
$("#pageBody").css("overflow", "scroll");
}
})
}
})
});
</script>
And this is my PHP
<?php include "db.php"; ?>
<?php
if (isset($_POST['user'])) {
$password = $_POST['user'];
$query = $connect->prepare("
SELECT firstName, lastName, color1, color2, authorizationLevel FROM employee WHERE password = ? LIMIT 1");
if(!$query) {
echo "Query Failed because " . mysqli_error($connect);
}
$query->bind_param("s", $password);
$query->execute();
$result = $query->get_result();
if ($result) {
while($row = mysqli_fetch_assoc($result)) {
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$color1 = $row['color1'];
$color2 = $row['color2'];
$authorizationLevel = $row['authorizationLevel'];
session_start();
$_SESSION['firstName'] = $firstName;
$_SESSION['lastName'] = $lastName;
$_SESSION['color1'] = $color1;
$_SESSION['color2'] = $color2;
$_SESSION['authorizationLevel'] = $authorizationLevel;
$array[] = array (
'firstName'=>$firstName,
'lastName'=>$lastName,
'color1'=>$color1,
'color2'=>$color2,
'authorizationLevel'=>$authorizationLevel
);
}
header('Content-type: application/json');
echo json_encode($array);
}
}
?>
I am trying to check the id's validity using ajax and codeigniter. when The status of the id if it is taken will appear "NPP tidak ada di database".
my contrroler:
public function ajax_add()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'level' => $this->input->post('level'),
);
$insert = $this->user_model->save($data);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
$id = $this->input->post('id');
$result = $this->user->checknpp( $id ); #send the post variable to the model
//value got from the get metho
$id= $id;
if( $result == '0' )
{
$data['inputerror'][] = 'id';
$data['error_string'][] = 'NPP tidak ada di database';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
My modal:
public function checknpp($id)
{
$this->db->select('id');
$this->db->where('id', $id);
$this->db->from('id', 1);
$query = $this->db->get();
if( $query->num_rows() > 0 ){ return 0; }
else{ return 1; }
}
My js:
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('user/ajax_add')?>";
} else {
url = "<?php echo site_url('user/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
my view:
<input name="id" id="masukpun" placeholder="NPP" class="form-control" type="text" />
However, when I run it, it always says that error updating/adding data.
Just try this,
public function ajax_add() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
$id = $this->input->post('id');
$result = $this->user->checknpp($id); #send the post variable to the model
//value got from the get metho
$id = $id;
if ($result == '0') {
$data['inputerror'][] = 'id';
$data['error_string'][] = 'NPP tidak ada di database';
$data['status'] = FALSE;
} else {
$data = array(
'id' => $this->input->post('id'),
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'level' => $this->input->post('level'),
);
$insert = $this->user_model->save($data);
$data = array("status" => TRUE);
}
echo json_encode($data);
}
Well, yesterday I started learning how to use AJAX and well I saw this page: http://www.formget.com/submit-form-using-ajax-php-and-jquery/ where everything was well explained. So, I coded the next:
if(isset($_POST['edited'])) {
$real_name = mysqli_real_escape_string($conn, $_POST['real_name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$date_day = mysqli_real_escape_string($conn, $_POST['date_day']);
$date_month = mysqli_real_escape_string($conn, $_POST['date_month']);
$date_year = mysqli_real_escape_string($conn, $_POST['date_year']);
$final_date = $date_day."-".$date_month."-".$date_year;
$location = mysqli_real_escape_string($conn, $_POST['location']);
$web_title = mysqli_real_escape_string($conn, $_POST['web_title']);
$web_url = mysqli_real_escape_string($conn, $_POST['web_url']);
$skype = mysqli_real_escape_string($conn, $_POST['skype']);
if($my_stats['real_name'] != $_POST['real_name']) {
mysqli_query($conn, "UPDATE users SET real_name = '$real_name' WHERE id = '$my_id'");
}
if($my_stats['email'] != $_POST['email']) {
$act = md5(time());
mysqli_query($conn, "UPDATE users SET email = '$email' WHERE id = '$my_id'");
mysqli_query($conn, "UPDATE users SET activation = '$act' WHERE id = '$my_id'");
mail($email, 'GimmeAHit! - Activación de correo', '¡Hola! Para activar tu cuenta visita el siguiente link: http://'.$_SERVER['SERVER_NAME'].'/?action=act&code='.$act);
}
if($my_stats['gender'] != $_POST['gender']) {
mysqli_query($conn, "UPDATE users SET gender = '$gender' WHERE id = '$my_id'");
}
if($my_stats['birthdate'] != $final_date) {
mysqli_query($conn, "UPDATE users SET birthdate = '$final_date' WHERE id = '$my_id'");
}
if($my_stats['location'] != $_POST['location']) {
mysqli_query($conn, "UPDATE users SET location = '$location' WHERE id = '$my_id'");
}
if($my_stats['web_title'] != $_POST['web_title']) {
mysqli_query($conn, "UPDATE users SET web_title = '$web_title' WHERE id = '$my_id'");
}
if($my_stats['web_url'] != $_POST['web_url']) {
mysqli_query($conn, "UPDATE users SET web_url = '$web_url' WHERE id = '$my_id'");
}
if($my_stats['skype'] != $_POST['skype']) {
mysqli_query($conn, "UPDATE users SET skype = '$skype' WHERE id = '$my_id'");
}
}
And my AJAX call:
echo '<script>
function showUpdateNode(elem) {
elem.parentNode.childNodes[1].style.display = "none";
elem.parentNode.childNodes[2].style.display = "inline";
elem.parentNode.childNodes[3].style.display = "none";
}
function sendSForm() {
var real_name = document.getElementById("real_name").value;
var date_day = document.getElementById("day_select").value;
var date_month = document.getElementById("month_select").value;
var date_year = document.getElementById("year_select").value;
var gender = document.getElementById("gender").value;
var location = document.getElementById("location").value;
var web_title = document.getElementById("website_title").value;
var web_url = document.getElementById("website_url").value;
var skype = document.getElementById("skype").value;
var email = document.getElementById("email").value;
var dataString = "real_name="+real_name+"&date_day="+date_day+"&date_month="+date_month+"&date_year="+date_year+"&gender="+gender+"&location="+location+"&web_title="+web_title+"&web_url="+web_url+"&skype="+skype+"&email="+email+"&edited=a";
$.ajax({
type: "POST",
url: "/sources/edit_profile.php",
data: dataString,
cache: false,
success: function() {
document.location.reload(true);
}
});
return false;
}
</script>';
Everything is in the same file, but for some reason when I make the AJAX call, nothing happens...
I tried to know what exactly happens, with success: function(html) {alert(html);} and if(isset($_POST['edited']) {echo "Okay!";} but the alert is empty!..
Maybe something is wrong with the dataString variable, what can you see where I went wrong? Any suggetion?
Edit There aren't errors in the console :/ (I think that the error is in PHP, but where, I think all is right...)
I am having a little trouble figuring out why my ajax response is sending me the entire page.
I am not using conventional AJAX code simply because this is how the guy was doing it in a tutorial I was following. I am using firebug to track all my javascript variables and when I break the code at the responseText var it gives me the entire page. Here is the code for the javascript on the page I am working with :
function changepass() {
var u = _("username").value;
var cp = _("currentPass").value;
var np = _("newPass").value;
var cnp = _("confirmNewPass").value;
if(np != cnp) {
_("status").innerHTML = "The passwords given do not match!";
} else if (cp === "" || np === "" || cnp === "") {
_("status").innerHTML = "Please fill out all of the fields.";
} else {
_("changepassbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "change_password.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var response = ajax.responseText;
if(response == "success"){
_("status").innerHTML = "Your password change was successful! Click the button below to proceed.<br><br>Back To Home Page";
} else if (response == "no_exist"){
_("status").innerHTML = "Your current password was entered incorrectly.";
_("changepassbtn").style.display = "initial";
} else if(response == "pass_failed"){
_("status").innerHTML = "Change password function failed to execute!";
_("changepassbtn").style.display = "initial";
} else {
_("status").innerHTML = "An unknown error occurred";
_("changepassbtn").style.display = "initial";
}
}
}
ajax.send("u="+u+"&cp="+cp+"&np="+np+"&cnp"+cnp);
}
}
Here is the AJAX code that I use to handle the requests.
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Any help would be greatly appreciated.
Thanks!
Here is the server side PHP:
if(isset($_POST["u"]) && isset($_POST['oe']) && isset($_POST['ne']) && isset($_POST['p'])) {
$oe = mysqli_real_escape_string($db_conx, $_POST['oe']);
$ne = mysqli_real_escape_string($db_conx, $_POST['ne']);
$p = md5($_POST['p']);
$u = mysqli_real_escape_string($db_conx, $_POST['u']);
var_dump($oe, $ne, $p, $u);
$sql = "SELECT username, password, email FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_username = $row[0];
$db_password = $row[1];
$db_email = $row[2];
var_dump($db_username, $db_password, $db_email);
if($db_email != $oe) {
echo "bad_email";
exit();
} else if($db_password != $p) {
echo "no_exist";
exit();
} else {
$sql = "UPDATE users SET email='$ne' WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$sql = "SELECT email FROM users WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_newemail = $row[0];
if($db_newemail == $ne) {
echo "success";
exit();
} else {
echo "email_failed";
exit();
}
}
}
My mistake was a simple syntax error. Gosh PHP is picky! The error occurs in the ajax.send command. I am miss an '=' on the last parameter.
Thanks for your help guys!
This is the JavaScript code which checks for the validation of the mobile number data (with other data) and forwards it to validate_user.php which stores the mobile number.
But I want to store the data of only those users whose mobile number exists in another table or else I want to display an error message saying 'User not present in the database'.
I need help. What do I do?
Thanks in advance.
JavaScript
$(document).ready(function() {
$("#user_submit_form").submit(function() {
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
if (mobile.length != 10 || !(mobile[0] == 7 || mobile[0] == 8 || mobile[0] == 9)) {
alert('Please enter a valid mobile number');
} else {
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
}); // End ajax method
alert('Thank You');
window.location.reload();
}
});
});
This is the server side PHP code:
<?php
session_start();
require("config/config.php");
if(isset($_POST['user_submit']))
$mobile =mysql_real_escape_string ($_POST['mobile']);
$dob = mysql_real_escape_string($_POST['dob']);
$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 mobile FROM mobile_db WHERE mobile="'.$mobile.'"');
if(mysql_num_rows($sql) == 1)
{
$query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,company,designation,home_business,add1,add2,city,state,pincode,timestamp) VALUES("'.$mobile.'","'.$dob.'",'.strval(time()).')';
$sql1= mysql_query($query);
}
else
{
return true;
}
?>
$(document).ready(function() {
$("#user_submit_form").submit(function() {
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
if (mobile.length != 10 || !(mobile[0] == 7 || mobile[0] == 8 || mobile[0] == 9)) {
alert('Please enter a valid mobile number');
} else {
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success: function(json){
if(json.error){
alert(json.error)// or do whatever you want
}
else{
alert(json.success) // there your made a success call the do your staff
}
}
}); // End ajax method
alert('Thank You');
window.location.reload();
}
});
});
**The Server Side php**
<?php
session_start();
require("config/config.php");
if(isset($_POST['user_submit']))
$mobile =mysql_real_escape_string ($_POST['mobile']);
$dob = mysql_real_escape_string($_POST['dob']);
$hostname = '';
$database = '';
$username = '';
$password = '';
$json = array();
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
$json['error'] = "Unable to Connect server!".mysql_error();
}
if(empty($json)){
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT mobile FROM mobile_db WHERE mobile="'.$mobile.'"');
if(mysql_num_rows($sql) == 1)
{
$query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,company,designation,home_business,add1,add2,city,state,pincode,timestamp) VALUES("'.$mobile.'","'.$dob.'",'.strval(time()).')';
$sql1= mysql_query($query);
$json['success'] = "Successfully inserted";
}
else
{
$json['error'] = 'A Fake Number';
}
}
echo json_encode($json);
You can verify this using success response
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success:(function(result){
if(empty(result)){
return false;
}else{
return true;
}
}));
});