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);
}
}
?>
Related
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";
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);
}
I want to make an ajax request on click with jquery, but it's not working:
This is what I have:
The button:
$photos_box .= '<a id="' . $imgID . '" class="like_button">' . $like . '</a>';
Maybe there's an error in the script:
// Like function
$('.like_button').click(function() {
$(this).toggleClass('liked');
var status = '';
if ($(this).hasClass('liked')) {
status = 'like';
$(this).html('Ya no me gusta');
console.log('like_works');
} else {
status = 'unlike';
$(this).html('Me gusta');
console.log('unlike_works');
}
var data = {
img_id : this.id,
sta : status
};
$.ajax({
type : 'POST',
url : '/includes/like.php',
data : data
}).done(function(reslike) {
if (reslike == 1) console.log('ajax_works');
});
});
And this is the like.php file:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
sec_session_start();
// User id
if (login_check($mysqli) == true) {
$user_id = $_SESSION['user_id'];
}
$img_id = $_POST['img_id'];
$status = $_POST['sta'];
$stmt = $mysqli->prepare("SELECT * FROM img_likes WHERE img_id = ? AND user_id = ?");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();
$usr_likes = $result->num_rows;
if ($status == 'like') {
if ($usr_likes == 0) {
$stmt->close();
$stmt = $mysqli->prepare("INSERT INTO img_likes (img_id, user_id) VALUES(?, ?)");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
}
}
else if ($status == 'unlike') {
if ($usr_likes != 0) {
$stmt->close();
$stmt = $mysqli->prepare("DELETE FROM img_likes WHERE img_id = ? AND user_id = ?");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
}
}
}
At last! Thanks to everyone. Hope my code help someone.
Check the URL in your ajax request, I'm not certain but I don't think '../includes/like.php' is a valid URL I think you actually have to give it a valid server URL like "http://example.com/includes/like.php"
My problem now when I click on the picture on my page, for the first time it will display. But for the second time it will display fail. This process will start by sending the data to ajax, then ajax(prosess.js) will send it to the php page(process1.php).
When I remove the code in blockquote ($query = "SELECT ...") it will run, but if not, it will display fail.
process1.php
<?php
include 'session.php';
include 'connection.php';
if(isset($_POST['dataS'])) {
$table = $_POST['table'];
$concat = "";
$serial = $_POST['dataS'];
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if($row) {
$prodName = $row['prodName'];
$quanProd = 1;
$priceProd = $_POST['total'] + $row['salePrice'];
if($table == "") {
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
$priceProd = number_format((float)$priceProd, 2, '.', '');
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "1",
"concat" => $concat,
"quantity" => $quanProd,
"price" => $priceProd,
)
);
}
else {
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "0",
)
);
}
}
?>
process.js
$(document).ready(
function() {
$("body").on("click","#product .add",
function(e) {
var total = document.getElementById("total").value;
var table = document.getElementById('table-list').innerHTML;
table = (table.trim) ? table.trim() : table.replace(/^\s+/,'');
var serial = $(this).attr('id');
var totalQ = document.getElementById("totalQ").value;
if(total == "")
total = 0;
else
total = parseFloat(total);
if(totalQ == "")
totalQ = 0;
else
totalQ = parseInt(totalQ);
var dataS = serial;
e.preventDefault();
$.ajax({
type : "POST",
url : "process1.php",
crossDomain: true,
data : {dataS : dataS, table : table, total : total},
dataType : 'json',
})
.done(function(html) {
if(html.success == 1) {
console.log('done: %o', html);
$("#table-list").html(html.concat).show();
document.getElementById('totalQuantity').innerHTML = html.quantity;
document.getElementById("total").value = html.price;
document.getElementById("payment").value = html.price;
document.getElementById('totalQ').value = html.quantity;
document.getElementById('title').innerHTML = html.price;
document.getElementById('input').value='';
$("#input").focus();
}
else {
alert("Wrong serial number!");
document.getElementById('input').value='';
$("#input").focus();
}
})
.fail(function(html) {
console.info('fail: %o', html);
alert("fail");
});
return false;
});
});
connection.php
<?php
$conn = mysqli_connect('localhost','root','','rds');
?>
your query is wrong:try this
$query = "SELECT prodName FROM product WHERE prodName = '".$item."'";
According to your pictures, your problem is that your database connection isn't correct. When you execute the first request it won't do any database interaction (because off the blocknotes). The second request you will send table data, which will perform a query. So the first request will succeed, while the second request will give you an error on your mysqli ($conn) object.
if($table == "") {
//Database interaction
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
//No database interaction because of the blocknotes
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
Check your the username, password and database name. I'm pretty sure you used something wrong here. As mentioned in your connection.php file you don't use a password. Are you sure the user root doens't have a password? Can you access the database with a MySQL administration tool like phpMyAdmin?
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!