How to submit a form with ajax and php - php

I am trying to add a change password function on my site. I decided that i would try using ajax so the site does not have to update itself. But i have one problem. When i submit the form to my PHP file nothing happends i just get the success from the ajax file. And the password is not change in my SQL db.
This is the html file.
<div class="boxPW">
<div class="boxInner">
<img class="closeBox" style="float: right;" src="images2/zoom/closebox.png" />
<h2>Endre passord ditt</h2>
<div id="lineBreak" style="margin-top: -19px; width: 70%;"></div>
<h4>Skriv inn et nytt passord for <?php echo $fname.' '.$lname.' ';?>
Vi anbefaler at du oppretter et unikt passord –
et du ikke bruker på noen andre nettsteder. <h4>
<div class="boxInner2">
<form id="changePw" name="changePw" method="POST" action="">
<input type="password" id="oldPw" name="oldPw" placeholder="Nåværende passord" />
<label id="error_oldPw" class="error">Fyll inn nåværende passord</label>
<p style="margin: 0; width:100px; font-size:9px; color: #38C6DA; ">Glemt ditt passord?</p>
<div class="divider"></div>
<input type="password" id="newPw" name="newPw" placeholder="Nytt passord"/>
<label id="error_newPw" class="error">Fyll inn nytt passord</label>
<div class="divider"></div>
<input type="password" id="conNewPw" name="conNewPw" placeholder="Bekreft nytt passord"/>
<label id="error_conNewPw" class="error">Gjenta ditt passord</label>
<div class="divider"></div>
<input id="buttonpw" class="button" type="button" name="submit" value="Endre passord" />
</form>
</div>
</div>
</div>
And here are my Jquery file (returnPwBox.js)
$(document).ready(function() {
$('.error').hide();
$('#buttonpw').click(function(){
//Validate inputData
$('error').hide();
var oldPw = $("input#oldPw").val();
if(oldPw == ""){
$("label#error_oldPw").show();
$("input#oldPw").focus();
return false;
}
var newPw = $("input#newPw").val();
if(newPw == ""){
$("label#error_newPw").show();
$("input#newPw").focus();
return false;
}
var conNewPw = $("input#conNewPw").val();
if(conNewPw != newPw){
$("label#error_conNewPw").show();
$("input#conNewPw").focus();
return false;
}
var dataString = 'oldpw='+ oldPw + '&newPw=' + newPw + '&conNewPw=' + conNewPw;
$.ajax({
type: "POST",
url: "changePw.php",
data: dataString,
success: function(){
$('.boxInner2').html("<div id='message' style='width: 300px;'></div");
$('#message').html("<h2>Endring fullført</h2>")
.append("<h4>Ditt passord er nå endret</h44>")
.hide()
.fadeIn(1000, function(){
$('#message').append("<img id='checkmark' src='imgaes2/pitcharrow.gif'/>");
});
}
});
return false;
});
And here are my changePw.php:
<?php
include('conn.php');
require_once('auth.php');
include('fetchMemData.php');
function clean($str){
$str=#trim($str);
if(get_magic_quotes_gpc());{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$id=$_SESSION['SESS_MEMBER_ID'];
$oldPw = clean($_POST['oldPw']);
$newPw = clean($_POST['newPw']);
$conNewPw = clean($_POST['conNewPw']);
$oldPw = strip_tags($oldPw);
$newPw = strip_tags($newPw);
$conNewPw = strip_tags($conNewPw);
$oldPw = md5($oldPw);
$newPw = md5($newPw);
$conNewPw = md5($conNewPw);
if($oldPw == $password)
{
mysql_query("UPDATE reguser SET password='$newPw' WHERE mem_id='$id'");
}else{
echo ("Feil nåværende passord");
}
?>
If anyone see any errors or any suggestions, shout out! I need some help:)

Based on the code you wrote $password value is not asigned (unless you did it in another file) therefore $password is NULL , and the if:
if($oldPw == $password)
{
mysql_query("UPDATE reguser SET password='$newPw' WHERE mem_id='$id'");
}else{
echo ("Feil nåværende passord");
}
returns false

Related

How create an url dynamically in Jquery AJAX?

I have a reset password system in PHP.
First - the forgot password.php sends to the customer an email with a link to reset the password.
This one is composed of the email of the customer and a unique key code for resetting the password
this email is like :
Please click the following link to reset your password: .../resetpassword.php?email=pm.chaumien#me.com&code=5e1b876bb1e36
On this page... you have a form with 2 boxes for a new password.
<?php
include 'main.php';
// Output message
$email=$_GET['email'];
$code=$_GET['code'];
$msg = '';
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if (isset($_GET['email'], $_GET['code']) && !empty($_GET['code'])) {
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
$stmt = $pdo->prepare('SELECT * FROM accounts WHERE email = ? AND reset = ?');
$stmt->execute([$_GET['email'], $_GET['code']]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// If the account exists with the email and code
if ($account) {
if (isset($_POST['npassword'], $_POST['cpassword'])) {
if (strlen($_POST['npassword']) > 20 || strlen($_POST['npassword']) < 5) {
$msg = 'Password must be between 5 and 20 characters long!';
} else if ($_POST['npassword'] != $_POST['cpassword']) {
$msg = 'Passwords must match!';
} else {
$stmt = $pdo->prepare('UPDATE accounts SET password = ?, reset = "" WHERE email = ?');
// We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
$password = password_hash($_POST['npassword'], PASSWORD_DEFAULT);
$stmt->execute([$password, $_GET['email']]);
$msg = 'Password has been reset! You can now login!';
}
}
} else {
die('Incorrect email and/or code!');
}
} else {
die('Please provide the email and code!');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body id="register_bg">
<nav id="menu" class="fake_menu"></nav>
<div id="preloader">
<div data-loader="circle-side"></div>
</div>
<!-- End Preload -->
<div class="rsvp-form" id="login">
<aside>
<figure>
<img src="../img/logoBlack.png" width="64" height="64" data-retina="true" alt="" class="logo_sticky">
</figure>
<?php echo 'email='.$email.'&'.'code='.$code?>
<form action="resetpassword.php?email=<?=$_GET['email']?>&code=<?=$_GET['code']?" method="post">
<div class="form-group">
<label>Your password</label>
<input class="form-control" type="password" name="npassword" id="npassword">
<i class="icon_lock_alt"></i>
</div>
<div class="form-group">
<label>Confirm password</label>
<input class="form-control" type="password" name="cpassword" id="cpassword">
<i class="icon_lock_alt"></i>
</div>
<!-- Do Not Remove! -->
<p class="error"></p>
<p class="message"></p>
<!-- Do Not Remove! Ends! -->
<div id="pass-info" class="clearfix"></div>
<div class="text-right"><button type="submit" class="btn_1 rounded full-width add_top_30">Reset Password</button></div>
</form>
<!-- COMMON SCRIPTS -->
<script src="../js/jquery-2.2.4.min.js"></script>
<script src="../js/common_scripts.js"></script>
<script src="../js/main.js"></script>
<script src="../assets/validate.js"></script>
<script src="../assets/formreset.js"></script>
<!-- SPECIFIC SCRIPTS -->
<script src="../assets/pw_strenghtreset.js"></script>
</body>
For check this form I've a jquery with AJAX for the form action and the verification but on this one, it doesn't work.
$('.rsvp-form form').submit(function(event) {
var $password = $(this).find('input[id="npassword"]');
var $password1 = $(this).find('input[id="cpassword"]');
$('.rsvp-form p.error').show();
$('input[id="npassword"],input[id="cpassword"]').removeClass('error');
if ($password.val() === '') {
$('.rsvp-form p.error').addClass('active').html('<i class="fa fa-exclamation"></i> Veuillez saisir un mot de passe, svp !');
$password.addClass('error').focus();
return false;
}
if ($password1.val() === '') {
$('.rsvp-form p.error').addClass('active').html('<i class="fa fa-exclamation"></i> Veuillez saisir un mot de passe, svp !');
$password1.addClass('error').focus();
return false;
}
if ($password1.val() != $password.val()) {
$('.rsvp-form p.error').addClass('active').html('<i class="fa fa-exclamation"></i> les mots de passe ne correspondent pas !');
$password1.addClass('error').focus();
return false;
}
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find('input, button, textarea');
var serializedData = $form.serialize();
$inputs.prop('disabled', true);
request = $.ajax({
url: 'resetpassword.php?email=<?php echo $email; ?>&code=<?php echo $code; ?>',
type: 'post',
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
$('.rsvp-form p.error').hide();
$('.rsvp-form p.message').html('success, password was changed').fadeOut(10000);
$('.rsvp-form form').find('input[type=text], textarea, select').val('');
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
'The following error occured: '+
textStatus, errorThrown
);
});
request.always(function () {
$inputs.prop('disabled', false);
});
event.preventDefault();
});
});

What's wrong with my AJAX and PHP whern I call it to login?

I have some trouble with my login form using ajax and php, could somebody con solve this??
This is code html:
login.html
<div id="id01" class="modal">
<form class="modal-content animate" action="" method="POST" id="login-form">
<div class="container">
<label for="login-email"><b>Username</b></label>
<input type="text" placeholder="Enter Email" id="login-email" name="login-email" required>
<label for="login-password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="login-password" name="login-password" required>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label><br>
<span id="showError"></span>
<button type="submit" id="btn-login" name="btn-login">Login</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancel-btn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#btn-submit").click(function{
var login-email = $("#login-email").val();
var login-password = $("#login-password").val();
var error = $("#showError");
if(login-email != "" && login-password != ""){
$.ajax({
url: "checkLogin.php",
type: "POST",
data: { login-email: login-email, login-password: login-password},
success: function(response){
var msg = "";
if(response == "success"){
window.location = 'profile.php';
} else {
msg = "Tên đăng nhập hoặc mật khẩu không chính xác.";
}
$('#id01').css({"display": "block"});
error.html(msg);
}
});
} else {
error.html("Email đăng nhập hoặc mật khẩu không được bỏ trống.");
return false;
}
});
});
</script>
and this is code php
login.php
if(isset($_POST["btn-login"])){
$email = trim($_POST["login-email"]);
$password = trim($_POST["login-password"]);
$sql_login = "SELECT email, password, permission FROM users where email='$email' and password='$password'";
$db->query($sql_login);
$rows = $db->findOne();
$permission = $rows['permission'];
if($rows['email'] == $email && $rows['password'] == $password){
echo "success";
} else {
echo "fail";
}
exit();
}
It seem to be not to load into ajax and php code cause i've try so many time but i didn't know the bugs in here.
you call checkLogin.php but the code php is in login.php
In the login.php code, you check the btn-login but the post data from client have no btn-login
{ login-email: login-email, login-password: login-password}
so the if block will never work.
if(isset($_POST["btn-login"])){
...
}
you can change like this
if(isset($_POST["login-email"]) && isset($_POST["login-password"])){
...
}
It appears at first glance that your jQuery is referencing btn-submit but your html defines this as btn-login instead.

using ajax to login with php

I am trying to use window.location = "userpage.php"; after a successful login but the page does not redirect.
I am using Ajax and a modal form in my code
Everything works fine. I don't get any errors. I check the network headers. and there is no response in the network
I have not been able to figure out the issue.
I have tried
window.location.href
window.location.replace.
Nothing is working
need help
Thanks
This is part of the js file
$("#loginform").submit(function(event) {
//prevent default php processing
event.preventDefault();
//collect user inputs
var datatopost = $(this).serializeArray();
//send them to login.php using AJAX
$.ajax({
url: "login.php",
type: "POST",
data: datatopost,
success: function(data) {
if (data == "success") {
window.location = "user_page.php";
} else {
$("#loginmessage").html(data);
}
},
error: function() {
$("#loginmessage").html(
"<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later.</div>"
);$
}
});
});
This is part of my login.php file
//Start session
session_start();
//Connect to the database
include("connection.php");
...
$email = mysqli_real_escape_string($conn, $email);
$password = mysqli_real_escape_string($conn, $password);
$password = hash('sha256', $password);
//Run query: Check combinaton of email & password exists
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password' AND activation='activated'";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
//If email & password don't match print error
$count = mysqli_num_rows($result);
if ($count !== 1) {
echo '<div class="alert alert-danger">Wrong Username or Password</div>';
} else {
//log the user in: Set session variables
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
if (empty($_POST['remember'])) {
echo "success";
} else {
// todo logic for remember me
}
}
This is the form modal
//Start session
session_start();
//Connect to the database
include("connection.php");
...
<form method="post" class="login_form modal" id="loginform">
<div class="form-body">
<div class="form-head"><h3>Login form</h3></div>
<div class="form-logo"><img src="/dist/img/logo.svg" alt="" /></div>
<div id="loginmessage"></div>
<div class="form-inputs">
<p><input type="email" name="email" placeholder="email" /></p>
<p><input type="password" name="password" placeholder="Password" /></p>
</div>
<div class="login-session">
<div class="remember">
<input type="checkbox" id="remember" name="remember" value="remember" />
<label for="remember">Remember me</label>
</div>
<div class="">
Forgot my password
</div>
</div>
<div class="form-submit">
<input class="btn btn-primary" type="submit" value="log in"/>
<a class="btn btn-small" href="#signupform" rel="modal:open">register</a>
</div>
</div>
</form>
I finally found the solution to the issue.
In the index.js file:
success: function(data) {
if (data == "success") {
window.location = "user_page.php";`
was changed to:
success: function(data) {
if ($.trim(data) == "success") {
window.location = "user_page.php";`
Because the response message success for some reason had whitespace in it. I trimmed all whitespace and it worked.

How to stay on same page after login

I am building an event registration system which displays event registration list if the user is logged in without page refresh using Ajax. However, when I try to login I get undefined index name on line echo "Hello ".$_SESSION["name"]."<br/>"; in index.php. My code is:-
index.php:-
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Registration</title>
<link href="style.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<!--Login div-->
<div id="logincontainer">
<form id="loginform" method="post">
<h3>Login</h3>
<div class="display-error" style="display: none;"></div>
<input type="email" name="lemail" placeholder="Enter email address" required>
<input type="password" name="lpassword" placeholder="Enter password" required>
<input type="submit" value="Sign In">
<p>Forgot Password</p>
<p id="bottom">Don't have an account yet? Sign up</p>
</form>
</div>
<div id="signupcontainer">
<form id="registerform" method="post">
<h3>Register</h3>
<div class="display-error" style="display: none;"></div>
<input type="text" name="rname" placeholder="Full Name" required>
<input type="email" name="remail" placeholder="Enter valid email" required>
<input type="password" name="rpassword" placeholder="Password" required>
<input type="text" name="rmobile" maxlength="10" pattern="[0-9]{10}" placeholder="Mobile" required>
<input type="submit" value="Create Account">
<p id="bottom">Already have an account? Sign In</p>
</form>
</div>
<!--Testing refresh portion-->
<div id="after-login" style="display: none;">
<?php
echo "Hello ".$_SESSION["name"]."<br/>";
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
<!--Testing portion ends-->
</div>
<script>
$(document).ready(function(){
$("#loginform").submit(function(){
var data = $("#loginform").serialize();
checkRecords(data);
return false;
});
function checkRecords(data){
$.ajax({
url : 'loginprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(){
alert("Email/Password is Incorrect");
}
});
}
});
</script>
<!--Signup Ajax-->
<script>
$(document).ready(function(){
$("#registerform").submit(function(){
var data = $("#registerform").serialize();
signupRecords(data);
return false;
});
function signupRecords(data){
$.ajax({
url : 'signupprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
alert('You have successfully Signed Up \n Please Login now.');
setTimeout(function(){
location.reload();
},500);
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(jqXHR,exception){
console.log(jqXHR);
}
});
}
});
</script>
</body>
loginprocess.php
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
$errorMsg = "";
$email = trim($_POST["lemail"]);
$password = trim($_POST["lpassword"]);
if(empty($email)){
$errorMsg .= "<li>Email is required</li>";
}
else{
$email = filterEmail($email);
if($email == FALSE){
$errorMsg .= "<li>Invalid Email Format</li>";
}
}
if(empty($password)){
$errorMsg .= "<li>Password Required.</li>";
}
else{
$password = $password;
}
if(empty($errorMsg)){
$query = $db->prepare("SELECT password from users WHERE email = ?");
$query->execute(array($email));
$pwd = $query->fetchColumn();
if(password_verify($password, $pwd)){
$_SESSION['email'] = $email;
//Testing piece
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email']]);
exit;
}
else{
json_encode(['code'=>400, 'msg'=>'Invalid Email/Password']);
exit;
}
}
else{
echo json_encode(['code'=>404, 'msg'=>$errorMsg]);
}
?>
As far as I can see the problem is that after login call you DO NOT reload the #after-login container contents - you only show it.
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
In the other words the #after-login contents only load on the first page load (before login) and then are not updated by your ajax call (only then you would have access to $_SESSION["name"]).
IMHO proper solution would be to return the $_SESSION["name"] value in the loginprocess.php response and update it in the #after-login container before showing it (eg. use an empty span where the name should appear which you'll fill out on login).
//Something like
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("span#name_placeholder").text(data.name) //return name from loginprocess.php
$("#logincontainer").hide();
$("#after-login").show();
}
The best solution would to be to create a html element like this for the
<div id="after-login" style="display: none;">
<h5 id="Username"></h5>
<?php
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
then after this include the username in the json like this
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
//$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email'],'username'=>$nme]);
exit;
on the ajax call you can now access the json response with the username included and feed the span element with the username like this
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#username").test(data.username);
$("#logincontainer").hide();
$("#after-login").show();
}

JQuery login does not respond

I'm new to Jquery, and I'm trying to create a login page, using JQuery and PHP but it doesn't respond when I click the login button, what I want is that after the login is success it redirect to index.html.
here is the JQuery code :
<script type="text/javascript" >
$(document).ready(function() {
$("form#memberlogin").submit(function(e) {
dataString = $(this).serialize();
$.post("check_login.php", dataString, function(data) {
$('form#memberlogin').hide();
window.location="index.html"
});
e.preventDefault();
});
});
</script>
Here is my form code :
<form id="memberlogin" class="form-horizontal" method="post">
<fieldset>
<div class="input-prepend" title="Username" data-rel="tooltip">
<span class="add-on"><i class="icon-user"></i></span><input id="username" autofocus class="input-large span10" name="username" id="username" type="text" value="admin" />
</div>
<div class="clearfix"></div>
<div class="input-prepend" title="Password" data-rel="tooltip">
<span class="add-on"><i class="icon-lock"></i></span><input id="password" class="input-large span10" name="password" id="password" type="password" value="admin123456" />
</div>
<div class="clearfix"></div>
<div class="input-prepend">
<label class="remember" for="remember"><input type="checkbox" id="remember" />Remember me</label>
</div>
<div class="clearfix"></div>
<p class="center span5">
<button type="submit" class="btn btn-primary">Login</button>
</p>
</fieldset>
</form>
And this is my php code :
<?php
ob_start();
$con=mysql_connect(localhost,"root","-----");
if(!con)
{
die(mysql_error());
exit();
}
mysql_select_db("sure") or die(mysql_error());
$user=$_POST['username'];
$pass=$_POST['password'];
if(get_magic_quotes_gpc()){
$user = stripslashes($user); //mencegah mysql injection
$pass = stripslashes($pass);
}
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$result=mysql_query("SELECT * FROM user WHERE username='$user' and password='$pass'") or die(mysql_error());
$count=mysql_num_rows($result);
if($count==1)
{
session_register("user");
session_register("pass");
$_SESSION['username']=$_POST['user'];
$_SESSION['id']=mysql_result($result,0,'id');
echo 'correct';
header("location:index.html");
}
else
{
die("id atau password anda salah");
exit();
}
mysql_close($con);
ob_end_flush();
?>
try with this code.
if($count==1)
{
session_register("user");
session_register("pass");
$_SESSION['username']=$_POST['user'];
$_SESSION['id']=mysql_result($result,0,'id');
echo 'Y';
//header("location:index.html");
}
else
{
die("id atau password anda salah");
exit();
}
in javascript:
$.post("check_login.php", dataString, function(data) {
// data is the response sent from the check_login.php
// display the type of data
console.log( typeof data );
console.log( data );
// if data is Y
var reg = /Y/g;
// regex to check the result
if( reg.test(data) ){
console.log('IN');
$('form#memberlogin').hide();
//top.location.href = "index.html";
} else {
console.log('OUT');
// PHP dies message here.
//alert(data);
}
return false;
});
try to check the response in firebug console tab.
Try to use href like,
window.location.href="index.html"
Read this What's the difference between window.location= and window.location.replace()?

Categories