Login form using PHP and AJAX - javascript

I am simply trying to log in on a popup log in box. I used AJAX to check whether log in is successful or not. If it is successful move to header location otherwise Give an error.
Code look like this:
<script>
$(document).ready(function () {
$('#login').click(function () {
var email = $("#email").val();
var pass = $("#pass").val();
var dataString = 'email=' + email + '&pass=' + pass;
if ($.trim(email).length > 0 && $.trim(pass).length > 0) {
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: dataString,
cache: false,
success: function (data) {
if (data) {
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
//or
window.location.href = "index.php";
}
else {
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
Form:
<div class="user_login">
<form action="" method="post">
<label>Email / Username</label>
<input type="email" Placeholder="Email-id" name="email" Required="required" id="email"/>
<br />
<label>Password</label>
<input type="password" Placeholder="Password" name="pass" Required="required" id="pass"/>
<br />
<div class="checkbox">
<input id="remember" type="checkbox" />
<label for="remember">Remember me on this computer</label>
</div>
<div class="action_btns">
<div class="one_half"><i class="fa fa-angle-double-left"></i> Back</div>
<div class="xyx"><input type="submit" value="Login" name="submitm" id="login"/></div>
<div id="error"></div>
</div>
</form>
Forgot password?
</div>
and php file is separate named as ajaxlogin.php:
include('includes/db.php');
if (isset($_POST['email']) && isset($_POST['pass'])) {
$pass = $_POST['pass'];
$email = $_POST['email'];
$query = "SELECT * FROM login WHERE email='$email' AND BINARY pass=BINARY '$pass'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$_SESSION['user'] = $email;
}
}
Both Script and form are on same page. Output that i am currently getting is Error message Both for right and wrong Username/Password Match. But if i delete "return false;" from script it moves to header location without log in.

try this script,
$(document).ready(function()
{
$('#login').click(function()
{
var email = $("#email").val();
var pass = $("#pass").val();
if ($.trim(email).length > 0 && $.trim(pass).length > 0)
{
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: {email:email,pass:pass},
cache: false,
success: function(data) {
if (data)
{
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
window.location.href = "index.php";
}
else
{
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});

Looks like you are not returning any data from ajaxlogin.php
so the success function always takes control to else and throws you an error message on the screen.

Related

Using AJAX when submitting forms

I'm very new to form submission with AJAX and have been following many tutorials on it's use, however I cannot seem to get it working in my current scenario.
I have a modal with a form inside of it linked to a PHP script and some JQuery AJAX.
When i submit the form the page appears white, I'm fairly sure this is because of the conditional logic in my PHP script.
So, where I have $stmt->rowCount() and the conditional logic it returns nothing as the script does nothing at this point.
Can I link this logic to AJAX success or failure or do I have to return a boolean from my script?
I know this is probably considered a silly question but some clarity would be of great use.
Form
<form id="userForm" method="post" action="test/process_data.php">
<div class="form-group">
<label for="email">First name:</label>
<input type="text" class="form-control" name="forename" id="forename" placeholder="E.g John" required>
</div>
<div class="form-group">
<label for="email">Surname:</label>
<input type="text" class="form-control" name="surname" id="surname" placeholder="E.g Smith" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="someone#example.com">
</div>
<div class="form-group">
<label for="company">Company:</label>
<input type="text" class="form-control" name="company" id="company" placeholder="Company name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
Just take me to the partner
</form>
AJAX Script
<script>
$("#userForm").submit(function(e) {
var forename = $('#forename').val();
var surname = $('#surname').val();
var email = $('#email').val();
var company = $('#company').val();
$.ajax({
url: "process_data.php",
type: "POST",
data: {
"forename" : forename,
"surname" : surname,
"email" : email,
"company" : company
},
success: function(data){
$("#forename").val('');
$("#surname").val('');
$("#email").val('');
$("#company").val('');
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
}
</script>
PHP Script to handle data
if (empty($_POST["forename"]) ||
empty($_POST["surname"]) ||
empty($_POST["email"]) ||
empty($_POST["company"]))
{
}
else{
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email_address = $_POST['email'];
$company_name = $_POST['company'];
$id = rand();
$date_time = date('Y-m-d');
try
{
// Construct the SQL to add a book to the database
$sql = "INSERT INTO user_data (forename, surname, email_address, company_name, id, date_time)
VALUES (:forename, :surname, :email_address, :company_name, :id, :date_time)";
// Prepare the SQL and bind parameters
$stmt = $conn->prepare($sql);
$stmt->bindParam(':forename', $forename);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':email_address', $email_address);
$stmt->bindParam(':company_name', $company_name);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':date_time', $date_time);
$stmt->execute();
// If the statement affected the database
if ($stmt->rowCount() > 0)
{
}
else{
}
} catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
Use serialize() method on the form to define the data property in your ajax call. Also added error handling.
$.ajax({
url: "process_data.php",
type: "POST",
data: $("#userForm").serialize(),
success: function(data){
//Successful
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
if (!window.console) console = { log: function () { } };
console.log(JSON.stringify(XMLHttpRequest), textStatus, errorThrown);
}
});
Use preventDefault(); before sending ajax request. Now when the form is done submitting you can do like this.
<script>
$("#userForm").submit(function(e) {
var forename = $('#forename').val();
var surname = $('#surname').val();
var email = $('#email').val();
var company = $('#company').val();
e.preventDefault(); // avoid to execute the actual submit of the form.
$.ajax({
url: "process_data.php",
type: "POST",
data: {
"forename" : forename,
"surname" : surname,
"email" : email,
"company" : company
},
success: function(data){
}
});
$("#userForm").fadeOut(800, function()
{
$(this)[0].reset();
}).fadeIn(800);
}
</script>

Login on same page, check SESSION without reload

I currently have a form at the top of every page on my website that lets the user input the username and password to login.
but Once the button is clicked, I use JQuery AJAX method to submit it to login.php without page refresh where it validates credentials and returns users whether the username / password submitted was valid or invalid.
Finally, the result is returned back to the page the user tried to login on.
I would also like the page to after once there is a successful login, the form disappears and is replaced with "Welcome back, USER!"
Everything works except for I want this to happen without a page reload. Here is what I have so far:-
Display form if session is not set, otherwise say Welcome back, user:-
<div class="user">
<?php
if (isset($_SESSION['logged_user'])) {
$logged_user = $_SESSION['logged_user'];
print("<p>Welcome back, $logged_user!</p>");
}
else {
print('<div class="forms">
<form id="login">
<label>Username <input type="text" name="username" id="username"></label>
<label>Password <input type="text" name="password" id="password"></label>
<input type="submit" class="submit" value="Login" id="login">
<span class="error"></span>
</form>
</div>');
}
?>
</div>
Javascript / AJAX to handle submission:
$(document).ready(function() {
$("#login").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+'&password='+password;
if(username != '' && password != '') {
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
success: function(responseText) {
if(responseText == 0) {
$("error").html("Invalid login.");
}
else if(responseText == 1) {
window.location = 'index.php';
}
else {
alert('Error');
}
}
});
}
return false;
});
And my login.php does everything fine.
Right now, the only way for my page to update to show the Welcome back message is if I include the line: window.location = 'index.php'; so that the page reloads. But without this, the user will have logged in successfully but will not be able to see this.
Is there a way to do this without AngularJS? This is for a class and we are not allowed to use frameworks, which has been quite frustrating! Thanks!
You can use Dynamic HTML (DHTML).
The success function you don't redirect instead using jquery to change the content.
Something like this:
success: function(responseText) {
if(responseText == 0) {
alert('Invalid login');
}
else if(responseText == 1) {
// Success
$('#login').parent().append('<p>Welcome back, '+username+'!</p>');
$('#login').remove();
}
else {
alert('Another Invalid login');
}
}
The API Login return:
0 if invalid
1 if valid
use this code,
<div class="user">
<div class="after_login" style="display:none">
<?php
$logged_user = $_SESSION['logged_user'];
print("<p>Welcome back, $logged_user!</p>");?>
</div>
<div class = "before_login">
print('<div class="forms">
<form id="login">
<label>Username <input type="text" name="username" id="username"></label>
<label>Password <input type="text" name="password" id="password"></label>
<input type="submit" class="submit" value="Login" id="login">
<span class="error"></span>
</form>
</div>');
?>
</div>
</div>
in script use like this instead of:
window.location = 'index.php';
use below lines,
$('.after_login').show();
$('.before_login').hide();
You have to change some modification in your javascript code as below :
$(document).ready(function() {
$("#login").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+'&password='+password;
if(username != '' && password != '') {
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
dataType: "json",
success: function(responseText) {
if(responseText.status == 'invalid') {
$(".error").html("Invalid login.");
}
else if(responseText.status == 'valid') {
$('.after_login').html('Welcome back,'+responseText.username);
$('.after_login').show();
$('.before_login').hide();
}
else {
alert('Error');
}
}
});
}
return false;
});
In above example, I have added one extra line dataType: "json", So now you have need to send output in json format from your login.php and also some modification done in success.
$response = array();
// $result variable get result from your database
if(count($result) == 0)
{
$response['status'] = 'invalid';
}else{
$response['status'] = 'valid';
$response['username'] = $result['username'];
}
echo json_encode($response);
exit;
So your success become like that below
success: function(responseText) {
if(responseText.status == 'invalid') {
$(".error").html("Invalid login.");
}
else if(responseText.status == 'valid') {
$('.after_login').html('Welcome back,'+responseText.username);
$('.after_login').show();
$('.before_login').hide();
}
else {
alert('Error');
}
In your login.php, change success condition to output username instead of 1. So responseText will have the username on ajax callback.
Remove the final else condition in your ajax success, and do something like this in the success condition
$('.forms').html('<p>Welcome back, ' + responseText + '!</p>');
PHP:
if (isset($_SESSION['logged_user'])) {
$logged_user = $_SESSION['logged_user'];
//Leave out the print(Welcome...) part, it won't do anything because the page won't be refreshed.
}
else{
exit('1');
}
In the Ajax, don't worry about responseText == 0, just stick with ==1:
success: function(responseText) {
if(responseText == "1") {
alert("Nope");
}
else {
$("#successdiv").html("welcome...");
}

Form still submits even with preventDefault

I don't know what is wrong here. preventDefault should stop the form from submitting but it still proceeds to. I have an ajax call where it verifies if user is valid. If not, prevent from submitting. Else, proceed to login and home page.
Form
<form id="signIn" method="post" action="processForms.php">
<table cellspacing="10">
<tr id="errorSignIn" hidden="hidden">
<td class="centerItem errorMessage" colspan="3">
Incorrect Username and/or Password
</td>
</tr>
<tr>
<td><input type="text" id="username" name="username" autocomplete="off" autofocus required placeholder="Username..."></td>
<td><input type="password" id="password" name="password" autocomplete="off" required placeholder="Password..."></td>
<td><input type="submit" name="processButton" class="signIn" value="Sign-in" ></td>
</tr>
</table>
</form>
Javascript
$('#signIn').submit ( function (e) {
var username = $('#username').val();
var password = $('#password').val();
var dataString = "username=" + username + "&password=" + password;
$.ajax( {
type: "POST",
url: "ajaxCheck.php",
data: dataString,
cache: false,
success: function (result) {
if (!result) {
$('#errorSignIn').removeAttr('hidden');
e.preventDefault();
return false;
}
}
});
});
ajaxCheck.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$password = md5($password);
$dbConnection = mysqli_connect('localhost','root','','onboard');
$query = "SELECT * FROM account WHERE username='$username' AND password='$password'";
$result = mysqli_query($dbConnection,$query);
$count = mysqli_num_rows($result);
if ($count == 1) { echo true; }
else { echo false; }
Because you are putting the prevent default inside the ajax success function which is an asynchronous. So that's why it's still submitting. You have to prevent it before calling the ajax and not after the ajax have finished.
$('#signIn').submit ( function (e) {
e.preventDefault(); // put preventDefault here not inside the ajax success function
var username = $('#username').val();
var password = $('#password').val();
var dataString = "username=" + username + "&password=" + password;
$.ajax( {
type: "POST",
url: "ajaxCheck.php",
data: dataString,
cache: false,
success: function (result) {
if (!result) {
$('#errorSignIn').removeAttr('hidden');
return false;
}
}
});
});
To answer your follow question here is something you can do.
var isFormChecked = false; // this variable will deremine if the ajax have finished what you wanted to do
$('#signIn').submit ( function (e) {
// if ajax set this to true, it will not go here when it triggers.
if(!isFormChecked){
e.preventDefault(); // put preventDefault here not inside the ajax success function
var username = $('#username').val();
var password = $('#password').val();
var dataString = "username=" + username + "&password=" + password;
$.ajax( {
type: "POST",
url: "ajaxCheck.php",
data: dataString,
cache: false,
success: function (result) {
// if result is set to true
isFormChecked = result;
// then trigger the submit of the form
$('#signIn').trigger('submit');
}
});
} else {
// form is submitted
isFormChecked = true;
}
});
What you can do is change the button type from submit to button in your html.
And then on click you validate , after that with the help of jquery you submit your form.
Here is how it will do your job:
<form id="signIn" method="post" action="processForms.php" >
<table cellspacing="10">
<tr id="errorSignIn" hidden="hidden">
<td class="centerItem errorMessage" colspan="3">
Incorrect Username and/or Password
</td>
</tr>
<tr>
<td><input type="text" id="username" name="username" autocomplete="off" autofocus required placeholder="Username..."></td>
<td><input type="password" id="password" name="password" autocomplete="off" required placeholder="Password..."></td>
<td><input type="button" name="processButton" class="signIn" value="Sign-in" ></td>
</tr>
</table>
</form>
$('#processButton').click ( function (e) {
var username = $('#username').val();
var password = $('#password').val();
var dataString = "username=" + username + "&password=" + password;
$.ajax( {
type: "POST",
url: "ajaxCheck.php",
data: dataString,
cache: false,
success: function (result) {
if (!result) {
$('#errorSignIn').removeAttr('hidden');
return false;
}
else { $("#signIn").submit(); }
}
});
});

How to display error messages Jquery ajax?

I am a student and am using jquery and php to add records to database. Records are being added, but i want to display a message "Record inserted" in the if the the record has been successfully been added and an error message if an error occurs.
This is my html code:
<form id="forn-newsletter" class="form-horizontal" method="POST">
<div class="form-group">
<label id="name_label" class="control-label col-xs-2">Name</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="news_name" name="news_name" placeholder="Name" onblur="checkName();"/><font color="red" id="name_error"></font>
</div>
</div>
<div class="form-group">
<label id="email_label" class="control-label col-xs-2">Email</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="news_email" name="news_email" placeholder="Email" onblur="vali()"/><font color="red" id="email_error"></font>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10">
<button id="register-newsletter" type="submit" class="btn btn-primary">Register for Newsletter</button>
</div>
</div>
<div id="dialog"></div>
</form>
This is my registration-newsletter.php
<?php
include('connect.php');
$name=$_POST['name'];
$email=$_POST['email'];
$val=md5($name.$email);
$query = "INSERT INTO newsletter (Id,Name,Email,Val) VALUES('','$name','$email','$val')";
$result=mysql_query($query);
if(!$result){
echo "Some error Occured..Please try later";
}
else{
echo "Your details have been saved. Thank You ";
}
mysql_close($con);
?>
This is my JQuery code
$(document).ready(function(){
$("#register-newsletter").click(function(){
var name=$("#news_name").val();
var email=$("#news_email").val();
var dataString="name="+name+"&email="+email;
var request;
request = $.ajax({
url: "registration-newsletter.php",
type: "POST",
data: dataString
});
//return false;
});
});
Add a span to your html code for displaying error.
<span id="error"></span>
Already you are echoing the message from PHP page to ajax. You can do mysql_affected_rows() to check whether the query updated the table.
$result=mysql_query($query);
if(mysql_affected_rows()>0){ // return the number of records that are inserted
echo "Your details have been saved. Thank You "; // success
}
else{
echo "Some error Occured..Please try later"; // failure
}
exit;
Then you can simply show the echoed message in the span with id error as:
request = $.ajax({
url: "registration-newsletter.php",
type: "POST",
data: dataString,
success:function(response) // response from requested PHP page
{
$('#error').html(response); // set the message as html of span
}
});
$.ajax({
url: 'registration-newsletter.php',
type: 'post',
data: dataString ,
success: function (msg) {
alert(msg);
},
error:function(msg)
{
alert(msg);
}
});
jQuery.ajax({
url: "myfile.php",
type: "POST",
data: dataString,
success:function(response) /* this response is an array which is returning from the myfile.php */
{
$status = response['status'];
if($status == 'success')
{
$('#message').html(response['msg']);
}
else
{
$('#message').html(response['msg']);
}
}
});
The function which you have added success will handle the "text to be append" or "alert to be show". Its quite equal to if condition, If the response came successfully, It will go into the condition.
This is what worked for me for form submit (see those 2 parameters to .then function):
<span id="result">Loading...</span>
<div id="form">
<form>
<input id="personId"> <-- put personID here<br>
<input id="submit" type="submit" value="Generate">
</form>
</div>
<script type="application/javascript">
$(document).ready(function() {
var submit = $('#submit');
var res = $('#result');
$('#form').submit(function() {
submit.prop('disabled', true);
res.text("Sending message...");
$.ajax({
url: '/rest/message',
contentType: "application/json;charset=UTF-8",
method: "POST",
data: JSON.stringify({'personId': $('#personId').val()})
}).then(function(result) { // OK
res.text("Message was generated");
submit.prop('disabled', false);
}, function(reason) { // ERROR
res.css('color', 'red').css('font-weight','Bold');
res.text("An error has occurred: " + reason.responseJSON.message);
submit.prop('disabled', false);
});
return false; // prevent default action
});
});
</script>
error: function(xhr) {
alert(xhr.responseText);
}
You can also get the HTTP status code or the generic message sent by your server (such as "Internal Server Error") in this XHR object if needed. More info : https://api.jquery.com/jQuery.ajax/#jqXHR

Validate input form using jquery with reCAPTCHA

I have a comment form which insert data to a database upon submitting. Following is the code;
function reloadRecaptcha() {
var publicKey = "*************************************";
var div = "recap";
Recaptcha.create(publicKey,div,{theme: "white"});
return false;
}
function validateForm() {
var x=document.forms["cmnts"]["name"].value;
if (x==null || x=="") {
jAlert('Please enter your name', 'Error');
return false;
}
var x=document.forms["cmnts"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
jAlert('Please enter a valid email address', 'Error');
return false;
}
var x=document.forms["cmnts"]["comment"].value;
if (x==null || x=="") {
jAlert('Please enter a comment', 'Error');
return false;
}
var challenge = Recaptcha.get_challenge();
var response = Recaptcha.get_response();
$.ajax({
type: "POST",
url: "includes/valrecaptcha.php",
async: false,
data: {
challenge: challenge,
response: response
},
success: function(resp) {
if(resp == "false") {
jAlert('Please enter captcha words correctly', 'Error');
reloadRecaptcha();
}
}
});
}
Everything (such as form validating works fine except when I hit the submit button, the comment is posted no matter the reCAPTCHA is correct or not. Right before the page starts navigating, I see the alert message. I'm using jAlert to display alert messages. Following is the form;
<h4>Leave your comment</h4>
<form action="blog?post=".$_GET["post"]."#comments" onsubmit="return validateForm();" name="cmnts" method="post">
<div class="form_row">
<label>Name</label><br />
<input type="text" class="tbox" name="name" title="Type your name"/>
</div>
<div class="form_row">
<label>Email (not visible to others)</label><br />
<input type="text" class="tbox" name="email" title="Type your email" />
</div>
<div class="form_row">
<label>Comment</label><br />
<textarea name="comment" class="tbox" rows="6" title="Type your comment" ></textarea>
<p>You may use following HTML tags and attributes: <b> <cite> <del> <i> <u></p>
</div>
<div class="form_row" style="height:80px;">
<label>Captcha</label><br />
<div id="recap"></div>
<p>I must make sure that you're <i>not</i> a spammer or a bot</p>
<div style="clear:both;">
</div>
<input value="Comment" id="submit" name="submit" class="submit_btn float_l" type="submit">
</form>
The <body> tag has an onload event return reloadRecaptcha();
So why doesn't the form get submitted before validating the reCAPTCHA?
This happens because validateForm() does not return anything from the ajax call. You should have a variable like isCaptchaValidated, and set that inside the success() of ajax, and then return that variable after the ajax like below:
var isCaptchaValidated = false;
$.ajax({
type: "POST",
url: "includes/valrecaptcha.php",
async: false,
data: {
challenge: challenge,
response: response
},
success: function(resp) {
if(resp == "false") {
jAlert('Please enter captcha words correctly', 'Error');
reloadRecaptcha();
} else {
isCaptchaValidated = true;
}
}
});
return isCaptchaValidated;
By the way, ajax means Asynchronous JavaScript and XML, so I would go against setting async: false.

Categories