PHP/JavaScript login script refreshing when form is submitted - javascript

I've created a login page using the following JavaScript:
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
//$("#submitButton",form).attr("disabled","disabled");
var e = $("#username", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
//var str = form.serialize();
//alert(str);
$.ajax({
type: 'POST',
url: 'http://localhost/php/log.php',
crossDomain: true,
data: {username: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location.replace("http://www.google.co.uk");
}
else {
alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "index.html";
}
});
}
else {
//if the username and password is empty
alert("You must enter username and password");
}
return false;
}
and the PHP in log.php is:
$link = mysql_connect("$host", "$username", "$password") or die("Could not connect to host.");
mysql_select_db("$db_name", $link) or die("Could not find database.");
$uname = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$sql = "SELECT * FROM user WHERE username = '$uname' AND password = '$password'";
$result=mysql_query($sql);
$num_row=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if (is_object($result) && $result->num_rows == 1) {
$response['success'] = true;
}
else
{
$response['success'] = false;
}
echo json_encode($response);
//echo 'OK';
I would expect the page to show some error if the combination is wrong, or redirect to a different page if it's correct. However it just refreshes with the username/password in the url.
Log in form
<form id="loginForm" method="post">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>

Since you're using jQuery (version 1.10.1), you can bind the click event directly to your forms submit button
$(document).on('click', '#submitButton', function(e) {
e.preventDefault();
... See detailed jsFiddle example ...
return false;
});
With preventDefault(), you remove the default submit behavior of the Submit button, so the page won't be reloaded after form submit.
Also use form attributes like action to provide ajax URL, or method, for setting ajax request type.
P.S This type of binding won't work for jQuery 1.6
jsFiddle example

Please change your html container as follows
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="button" value="Login" id="submitButton" onclick="handleLogin()">
Since, you are submitting data using ajax, then you dont need to writt "form" tag in your html
Total page would be refresh when click "Submit" button. so I have changed as "button" and provide the ajax method in "onclick" attribute
Sample PHP file (index.php) that I tried without connecting DB for testing yours scenario
<?php
if($_POST){
if($_POST['username'] == "admin" && $_POST['password'] == "admin"){
$response['success'] = true;
}else{
$response['success'] = false;
}
echo json_encode($response);
exit;
}
?>
modified your js code
function handleLogin() {
var e = $("#username").val();
var p = $("#password").val();
if(e != "" && p != "") {
$.ajax({
type: 'POST',
url: 'index.php',
crossDomain: true,
data: {username: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
}
else {
alert("Your login failed");
}
},
error: function(error){
alert('Could not connect to the database' + error);
}
});
}
else {
alert("You must enter username and password");
}
return false;
}

Try this: if(response.responseText)

Related

Using AJAX to authorise form with database value

I have a form that requires 'authorization' - where the user needs to enter one of the authorization codes stored in a database to be able to submit the form (basically a password). I'm trying to use AJAX with PHP to both display (using Bootstrap's feedback glyphicons) a tick or cross depending on whether or not the user entered a valid value and allow or prevent form submission. If the user did not enter a valid value, form submission is prevented.
My code below currently isn't working, any help would be greatly appreciated.
HTML:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>
<form name="auth_form" id="auth_form" method="post" action="action.php">
<p>Please enter authorisation code.</p>
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<input class="form-control" id="auth_code_input" autocomplete="new-password" name="auth_code_input" type="password" required>
<span class="form-control-feedback glyphicon" id="statusIcon"></span>
</div>
<button class="btn btn-success btn-ok" name="Submit" id="submit" type="Submit">Submit</button>
</form>
JS:
<script>
$(document).ready(function() {
// Validate on blur and display 'cross' icon in span if invalid, tick if valid
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
e.preventDefault();
}
});
// Validate on submit and prevent form submission if invalid
$('#auth_form').on('submit', function(e) {
if (!ValidateInput()) {
e.preventDefault();
}
})
});
// AJAX to check the auth-code server-side
function ValidateInput() {
var given_code = document.getElementById('auth_code_input').value;
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code
});
.done(function(response) {
var response = valid;
if valid = '1' {
$('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
}
.fail(function() {
IsValid = false;
$('#auth_code_input').val('Something went wrong, please try again.');
});
return IsValid;
});
</script>
checkauth.php
<?php
error_reporting(E_ALL);
ini_set( 'display_errors', 1);
$given_code = $_REQUEST['given_code'];
include 'pdo_config.php';
$valid = '0';
try {
$conn = new PDO($dsn, $user, $pass, $opt);
$stmt = $conn->prepare("SELECT instructor_id, auth_code FROM tbl_instructors WHERE auth_code = :given_code;");
$stmt->bindParam(':given_code', $given_code);
$stmt->execute();
$row = $stmt->fetchColumn();
if ($row == 1) { // row equals one, means auth-code corresponds to an instructor and is valid
$valid = '1';
} else {
$valid = '0';
}
echo valid;
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
found some errors in your js, function ValidateInput() {, plz update your code from below one.
function ValidateInput() {
var given_code = document.getElementById('auth_code_input').value;
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code
});
.done(function(response) {
if (response == '1') {
$('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
}
.fail(function() {
IsValid = false;
$('#auth_code_input').val('Something went wrong, please try again.');
});
return IsValid;
});
if it still not work, then plz add async: true in your ajax call like this,
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code,
async: true
});
It will work definitely

JQuery Display Alert Message on Form Submit

I am trying to display alert messages on jquery from the client side. The jquery will be called once the submit button is clicked. The form then will call the server side php. Here is my code:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
But the alert message does not pop up inside the $.postmethod
And I also want to know how I can pop up the alert message from the server side. Here is my sample code:
SERVER SIDE
<?php $query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>alert('ERROR')</script>";
return false;
} ?>
In summary, the code above works but I need to display messages that would tell me if the query is successful or not. Thanks
My new problem is that the code below bring me to another page:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
$('#formAdd').on('submit', function (e) {
e.preventDefault();
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.ajax({
context: this,
url: $(this).attr('action'),
type: 'POST',
data: new FormData(this),
dataType: 'json'
}).done(function (data) {
if(data == 'ok') {
alert("DATA SUCCESSFULLY ADDED");
}
if(data == 'no') {
alert("ERROR");
}
}).fail(function (data) {
console.log('failed');
});
});
});
SERVER
$query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
mysqli_close($conn);
echo json_encode('no');
return false;
}
I need to return after the json_encode because there are still methods below that.
HTML Form
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
Script :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
$(document).on('submit', "#formAdd", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "post",
data: $(this).serialize(),
error:function(){
alert("ERROR : CANNOT CONNECT TO SERVER");
},
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
PHP server side like this:
<?php
$insert = mysqli_query($conn, "insert query here");
if($insert) {
echo json_encode('ok');
} else {
echo json_encode('no');
}
?>
Just you need to put id="id" in input type text.
<input type="text" name="id">
Working Code
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" id="id" name="id">
<input type="submit" value="submit">
</form>

Can not get ajax callback to a function

I have a form for user to register new account. I use jquery + ajax to check availability of email address on form submission. In Jquery code I used e.preventDefault(); to prevent form submission if there is any error occurs. I tried the existed email address in the email input and click submit the form. It allows form to submit. It should not do this because ajax reponseText return true means that the email address is already existed in database.
Could anyone please tell me how to fix my code so that if ajax response returns true, it will prevent form submission and shows up errors.
I tried to read and follow this article but fails after so many attempts.
Here is my form:
<form role="form" method="post" id="signupForm" action="index.php?view=signup-gv">
<div class="col-xs-6 border-right">
<div class="form-group">
<label for="exampleInputEmail1">Full Name</label>
<input type="text" class="form-control" id="regname" name="regname" placeholder="Full Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label><span id="emailcheck"></span>
<input type="email" class="form-control" id="regemail" name="regemail" placeholder="Enter email">
</div>
</div>
<div class="form-group col-xs-6">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="regpass" name="regpass" placeholder="Password">
</div>
<button style="position:relative; left: 15px; top: 10px;" class="btn btn-default" name="register" id="register">Register</button>
</form>
Here my jquery code:
$(document).ready(function(){
$('#regname').focus();
$('#signupForm').submit(function(e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
if(regname.val() == ''){
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
e.preventDefault();
}
else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
e.preventDefault();
}
else if(regpass.val() == ''){
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
e.preventDefault();
}
emailCheck().done(function(r){
if(r){
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
e.preventDefault();
}
});
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {regemail:regemail.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'emailcheck.php',
success: function(responseText){
if(responseText == 0){
return false; // good to go
}
else{
emailcheck.html('<span class="errorss"> This email is existed.</span>');
return true; // This email is registered. Please try different one
}
}
});
}
First you are not returning anything from the emailCheck() function, but you are using it as if it is returning a promise object.
So
$(document).ready(function () {
$('#regname').focus();
$('#signupForm').submit(function (e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
//prevent the form submit
e.preventDefault();
if (regname.val() == '') {
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
} else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
} else if (regpass.val() == '') {
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
} else {
emailCheck().done(function (r) {
if (r) {
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
} else {
$('#signupForm')[0].submit();
}
});
}
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {
regemail: regemail.val()
};
var deferred = jQuery.Deferred();
$.ajax({
type: 'POST',
cache: false,
data: UrlToPass,
url: 'emailcheck.php',
success: function (responseText) {
if (responseText == 0) {
deferred.resolve(false);
} else {
emailcheck.html('<span class="errorss"> This email is existed.</span>');
deferred.resolve(true);
}
},
error: function () {
deferred.reject();
}
});
return deferred.promise();
}
You are confusing yourself with sync and async functions. An ajax function makes an Async call and returns output in its callback. You are trying to wrap an Async function inside a normal function and expecting it to behave synchronously.
Your function returns before the Ajax call receives its output. Use
async: false
$.ajax({
type : 'POST',
cache: false,
async: false,
data : UrlToPass,
Refer to following for dettails:
How to make JQuery-AJAX request synchronous

Submit form button stuck after ajax post

Hi i have a form which uses Ajax to make a post in Rails 4. The javascript runs some validation and should return an alert message once the post is successful. Currently the submit button stays depressed and although the form posts no message gets alerted. I dont know what i'm doing wrong and just want the form to alert a message and then reset itself.
$('#submit1').click(function(e){
e.preventDefault();
var name = $('input#name').val();
if (name == "") {
alert("please enter a name!");
$('input#name').focus();
return false;
}
var email = $('input#email').val();
if (email == ""){
alert("please enter your email");
$('input#email').focus();
return false;
}
var content = $('textarea#text').val();
if (content == ""){
alert("please enter a comment");
$('textarea#text').focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&content=' + content;
$.ajax({
type: "POST",
url: "emailer",
data: dataString,
dataType: 'json',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
success: function(){
alert("mappy jappy");
$('input#name').reset();
$('input#email').reset();
$('textarea#text').reset();
}
});
return false;
});
You are preventing the wrong event. You need the 'onsubmit' event of the form not the 'onclick' event of the submit button.
$('#myform').on('submit', function(event){
event.preventDefault();
/* your code here */
});
For more info please read :
How to prevent form from being submitted?
First of all the reset function is not for the text boxes..it will run for the form. So the corrected code would be...
<script>
$(function(){
$('#submit1').click(function(e){
e.preventDefault();
var name = $('input#name').val();
if (name == "") {
alert("please enter a name!");
$('input#name').focus();
return false;
}
var email = $('input#email').val();
if (email == ""){
alert("please enter your email");
$('input#email').focus();
return false;
}
var content = $('textarea#text').val();
if (content == ""){
alert("please enter a comment");
$('textarea#text').focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&content=' + content;
$.ajax({
type: "POST",
url: "user_availability.php",
data: dataString,
dataType: 'json',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
success: function(){
alert("mappy jappy");
$('#contact-form')[0].reset();
}
});
return false;
});
});
</script>
AND the html part would be like below-
<form id="contact-form" method="post" enctype="multipart/form-data">
<input type="text" id="email" name="email" />
<input type="text" id="name" name="name" />
<textarea name="text" id="text"></textarea>
<input type="submit" value="submit" id="submit1" />
</form>
Please Check and let me know...

Trigger event on submit

In a newsletter sign-up form, I would like to make the email disappear after the end user hits enter. I have already added JS to hide and unhide the placeholder text.
The code:
<form id="form" action="https://xxxx.com/subscribe/post-json?u=xxx&id=xx&c=?" method="GET">
<input type="hidden" name="u" value="xxx">
<input type="hidden" name="id" value="xxx">
<input id="email" type="EMAIL" autocapitalize="off" autocorrect="off" name="MERGE0" id="MERGE0" size="25" placeholder= "Type your email and press enter">
<p id="response"></p>
</form>
And the JS:
<script >
var text = document.getElementById("email");
text.onfocus = function() {
if ( text.placeholder == "Type your email and press enter") {
text.placeholder = "";
}
};
text.onblur = function() {
if ( text.placeholder == "") {
text.placeholder = "Type your email and press enter";
}
};
</script>
I tried to create a function to trigger the event but it still didn't work:
function checkEnter(event)
{
if (event.keyCode == 13) {text.placeholder = "cool";}
};
Could you all see what's wrong with my code?
Thank you.
You need to add a event listener for the enter key. You could remove your function checkEnter and use this instead:
document.querySelector('#email').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
if (key == 13) {
text.placeholder = "cool";
}
};
I have integrated the code below with the mailchimp form and got the desired results:
var paragraph = document.getElementById('response');
$('#form').submit(function(e) {
var $this = $(this);
$.ajax({
type: "GET", // GET & url for json slightly different
url: "https://xxxxx.com/subscribe/post-json?u=xxxx&id=xxx&c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
paragraph.innerHTML = data.msg;
text.placeholder = "Oopsy daisy! Error :-(";
form.reset();
} else {
paragraph.innerHTML = data.msg;
text.placeholder = "Thanks so much!";
form.reset();
}
}
});
return false;
});

Categories

Resources