Alert box does not work - javascript

I am trying to display an alert box and click on Ok to refresh the page. I have tried using window.location.reload(true)
I want to show a message before page reload. The problem is that the page reloads automatic but the alert box not showing.
HTML Content
<form action="<?php echo $action_link; ?>" method="post" name="form_Change_Password" id="form_Change_Password" class="form-horizontal" novalidate="novalidate">
<input type="hidden" name="id" value="<?php echo $admin_id; ?>">
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button> You have some form errors. Please check below.
</div>
<div class="alert alert-success display-hide">
<button class="close" data-close="alert"></button> Your form validation is successful!
</div>
<div class="form-group margin-top-20">
<label class="control-label col-md-3">Old Password
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa"></i>
<input type="password" class="form-control" name="old_password" id="old_password" value="">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">New Password
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa"></i>
<input type="password" class="form-control" name="new_password" id="new_password" value="">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Confirm Password
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa"></i>
<input type="password" class="form-control" name="confirm_password" id="confirm_password" value="">
</div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="button" class="btn green" name="btnChangePassword" onclick="newpassword(<?php echo $admin_id; ?>)">Update</button>
Cancel
</div>
</div>
</div>
</form>
Ajax Code:
$.ajax({
url: "<?php echo $action_link; ?>",
type: "POST",
data: {
'id': <?php echo $admin_id; ?>,
'old_pass': old_pass,
'new_pass': new_pass,
'conf_pass': conf_pass,
change_password : 'change_password'
},
success: function (result){
if(result == 1){
bootbox.alert('Password changed successfully.');
window.location.reload(true);
}else if(result == 2){
bootbox.alert('New password and confirm password does not match.');
return false;
}
else if(result == 0){
bootbox.alert('Old password does not match.');
}
},
error: function (result){
}
});
Action
if(isset($_REQUEST['change_password']) && $_REQUEST['change_password'] == 'change_password'){
ob_get_clean();
$id = $_REQUEST['id'];
$password = mysqli_real_escape_string($obj->CONN,md5($_REQUEST['old_pass']));
$dbpassword = $admin->select_password($id);
$newpass = $_REQUEST['new_pass'];
$confpass = $_REQUEST['conf_pass'];
if($dbpassword != $password){
echo 0; exit;
}elseif($newpass != $confpass){
echo 2; exit;
}
else{
$admin->update_password($id, md5($newpass), $current_date);
echo 1; exit;
}
}

You have to use bootbox callback :
bootbox.alert("Password changed successfully.", function() {
// any code you want to happen after the alert is dismissed
window.location.reload(true);
});
So it will be :
...
success: function (result){
if(result == 1){
bootbox.alert("Password changed successfully.", function() {
window.location.reload(true);
});
}else if(result == 2){
bootbox.alert("New password and confirm password does not match.", function() {
return false;
});
}else if(result == 0){
bootbox.alert('Old password does not match.');
}
},
...
Hope this helps.

Try using the following:
bootbox.alert('Password changed successfully.', function(){
window.location.reload(true);
});
Instead of:
bootbox.alert('Password changed successfully.');
window.location.reload(true);

Related

How to insert dynamic data and static input data to mysql using ajax, dynamic data will not insert

I have a modal form with static input fields and dynamic input fields.
currently the data is being sent to the mysql database, the static fields are being inserted into the database but the dynamic fields are not being inserted.
The form data has to inserted into three mysql tables. tables are orders, products and sma.
HTML input code
<div class="modal fade" tabindex="-1" role="dialog" id="insertModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="well form-horizontal" action="" method="post" id="">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Insert Order Details</h3>
</div><hr>
<fieldset>
<!-- Text input-->
<div class="form-group">
<label for="customer" class="col-md-4 control-label">Customer Name</label>
<div class="col-md-7 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="customer" id="customer" placeholder="Customer" class="form-control" type="text">
<label id="lblcustomer" style="color:red"></label>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label for="date" class="col-md-4 control-label">Date</label>
<div class="col-md-7 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
<input name="date" id="date" placeholder="Date" class="form-control" type="date">
<label id="lbldate" style="color:red"></label>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label for="invoice" class="col-md-4 control-label">Invoice</label>
<div class="col-md-7 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="invoice" id="invoice" placeholder="Invoice" class="form-control" type="text">
<label id="lblinvoice" style="color:red"></label>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group" id="container">
<label for="product" class="col-md-4 control-label">Product Description</label>
<div class="col-md-7 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea name="product[]" id="product" class="form-control" placeholder="Product Description"></textarea>
<label id="lblproduct" style="color:red"></label>
</div>
Add More
</div>
</div>
<!-- Text input-->
<div class="form-group" id="container1">
<label for="sma_number" class="col-md-4 control-label">SMA Number</label>
<div class="col-md-7 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-barcode"></i></span>
<input name="sma_number[]" id="sma_number" placeholder="SMA Number" class="form-control" type="text">
<label id="lblsma_number" style="color:red"></label>
</div>
Add More
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label for="ebay" class="col-md-4 control-label">eBay Item Number</label>
<div class="col-md-7 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-qrcode"></i></span>
<input name="ebay" id="ebay" placeholder="eBay Number" class="form-control" type="text">
<label id="lblebay" style="color:red"></label>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label for="shipper" class="col-md-4 control-label">Shipped With</label>
<div class="col-md-7 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-road"></i></span>
<select name="shipper" id="shipper" class="form-control selectpicker">
<option value=" ">Please select Shipping Company</option>
<option>DHL</option>
<option>TNT</option>
<option>FEDEX</option>
<option>AUSPOST</option>
<option>PickUp</option>
</select>
<label id="lblshipper" style="color:red"></label>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label for="tracking" class="col-md-4 control-label">Tracking Number</label>
<div class="col-md-7 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
<input name="tracking" id="tracking" placeholder="Tracking No" class="form-control" type="text">
<label id="lbltracking" style="color:red"></label>
</div>
</div>
</div>
</fieldset>
<!-- Button -->
<div class="modal-footer">
<input type="button" name="save" id="save" value="Save Order" class="btn btn-success">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
Ajax script
<script>
$(document).ready(function(e){
//Variables
var html = '<div class="form-group"><label class="col-md-4 control-label">Product</label><div class="col-md-6 inputGroupContainer1" style="padding-left: 20px"><input name="product[]" id="product[]" placeholder="Product" class="form-control" type="text"></div><button id="remove" class="btn btn-danger i_remove_me pull-left" >-</button></div';
var maxRows = 5;
var x = 1;
//Add Rows to the form
$("#add").click(function(e){
e.preventDefault();
if(x <= maxRows){
$("#container").append(html);
x++;
}
});
//Remove rows from the from
$("#container").on('click','#remove', function(e){
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
$(document).ready(function(e){
//Variables
var html1 = '<div class="form-group"><label class="col-md-4 control-label">SMA</label><div class="col-md-4 inputGroupContainer1" style="padding-left: 20px"><input name="sma_number[]" id="sma_number[]" placeholder="SMA Number" class="form-control" type="text"></div><button id="remove" class="btn btn-danger i_remove_me pull-left" >-</button></div';
var maxRows = 5;
var x = 1;
//Add Rows to the form
$("#add1").click(function(e){
e.preventDefault();
if(x <= maxRows){
$("#container1").append(html1);
x++;
}
});
//Remove rows from the from
$("#container1").on('click','#remove', function(e){
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
</script>
<script>
//datatable
$(document).ready(function() {
$("#emp_table_details").DataTable();
});
$(document).ready(function() {
//Save Or Insert Data
$(document).on('click', '#save', function() {
var customer = $("#customer").val();
var date = $("#date").val();
var invoice = $("#invoice").val();
var product = $("#product").val();
var sma_number = $("#sma_number").val();
var ebay = $("#ebay").val();
var shipper = $("#shipper").val();
var tracking = $("#tracking").val();
if (customer == "") {
$("#lblcustomer").html("Customer Name Required!");
} else if (date == "") {
$("#lbldate").html("Date Required!");
} else if (invoice == "") {
$("#lblinvoice").html("Invoice Number Required!");
} else if (product == "") {
$("#lblproduct").html("Product Required!");
} else if (sma_number == "") {
$("#lblsma_number").html("SMA Number Required!");
} else if (ebay == "") {
$("#lblebay").html("eBay Number Required!");
} else if (shipper == "") {
$("#lblshipper").html("Shipper Required!");
} else if (tracking == "") {
$("#lbltracking").html("Tracking Required!");
} else {
$.ajax({
url: "ajaxsave.php",
type: "post",
data: {
customer: customer,
date: date,
invoice: invoice,
product: product,
sma_number: sma_number,
ebay: ebay,
shipper: shipper,
tracking: tracking
},
success: function() {
alert('Your Data Save Sucessful');
//document.getElementById('insert_form').reset();
//$("#emp_table_details").load('select_data.php');
$("#insertModal").modal('hide');
location.reload();
}
});
}
});
</script>
PHP insert to MYSQL code
<?php include 'config/config.php'; ?>
<?php
global $con;
//if (isset($_POST)) {
$customer = $_POST['customer'];
$date = $_POST['date'];
$invoice = $_POST['invoice'];
$product = $_POST['product'];
$sma_number = $_POST['sma_number'];
$ebay = $_POST['ebay'];
$shipper = $_POST['shipper'];
$tracking = $_POST['tracking'];;
$sql = "INSERT INTO orders(customer, date, invoice, ebay, shipper, tracking)
VALUES('$customer','$date','$invoice','$ebay','$shipper','$tracking')";
$query = mysqli_query($con, $sql);
$newOrderId = mysqli_insert_id($con);
if($query){
$sql1 = "INSERT INTO products(id, product) VALUES('$newOrderId','$product')";
$sql2 = "INSERT INTO sma(id, sma_number) VALUES('$newOrderId','$sma_number')";
$result = mysqli_query($con,$sql1);
$result2 = mysqli_query($con,$sql2);
}
?>
Adapt your AJAX call as follows:
var form = $("#submissionForm")[0]; //remember to give your form name the id submissionForm
var formData = new FormData(form);
$.ajax({
url: "ajaxsave.php",
type: "post",
data: formData,
contentType: false,
cache: false,
processData: false,
async: true,
success: function() {
alert('Your Data Save Sucessful');
//document.getElementById('insert_form').reset();
//$("#emp_table_details").load('select_data.php');
$("#insertModal").modal('hide');
location.reload();
}
});
You can then check what values your PHP file receive by writing them to file as follows:
<?php
$output = "POSTed variables:\n";
$customer = $_POST['customer']; $output .= "customer = $customer\n";
$date = $_POST['date']; $output .= "date = $date\n";
$invoice = $_POST['invoice']; $output .= "invoice = $invoice\n";
$products = $_POST['product'];
if (is_array($products))
{
for ($i=0; $i<sizeof($products); $i++)
{
$products[$i]; //the value of the array at index i. Save each of these to the database
$output .= "product[".$i."] = $products[$i]\n";
}
}
$sma_number = $_POST['sma_number'];
if (is_array($sma_number))
{
for ($i=0; $i<sizeof($sma_number); $i++)
{
$sma_number[$i]; //the value of the array at index i. Save each of these to the database
$output .= "sma_number[".$i."] = $sma_number[$i]\n";
}
}
$ebay = $_POST['ebay']; $output .= "ebay = $ebay\n";
$shipper = $_POST['shipper']; $output .= "shipper = $shipper\n";
$tracking = $_POST['tracking']; $output .= "tracking = $tracking\n";
file_put_contents( 'POSTed_vars.txt', $output ); // DEBUG
?>
I tested the code by filling out your modal form with multiple products and multiple sma numbers. The text file POSTed_vars.txt contained the following, which was exactly what I inserted into the form. It is now just your job to write those values to the database.
POSTed variables:
customer = John Doe
date = 2019-10-05
invoice = inv12345
product[0] = Blue Teddy Bear
product[1] = Green Teddy Bear
product[2] = Red Teddy Bear
sma_number[0] = sma12345
sma_number[1] = sma67891
ebay = ebay12345
shipper = DHL
tracking = track12345
Hope it helps

How to create a login script using PHP and JAVASCRIPT?

I have a php file for comparing the inserted data in input element of HTML.
then, if I click the button, I want to trigger it by JavaScript.
I have a sample code with php, if I used this in html file, this works perfectly fine, but then I have no idea on how to use this in JavaScript.
<?php
include("php_functions/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$_SESSION['login_user'] = $myusername;
header("location: .php");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
echo '<script type="text/javascript">',
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
echo '}, 100);</script>';
}
}
?>
HTML:
<form action="" method="POST" id="index-login">
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="pwd"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input id="RememberMe" name="rememberme" type="checkbox" />
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<button type="submit" class="btn btn-primary hidden-xs" id="signin">
Sign In
</button>
<button
type="submit"
class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
id="signin1"
>
Sign In
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
</form>
First your code has alot of flops.
1.) You are saving password as plaintext, you will need to hash your password using php default password hashing mechanism.
2.) Your code is vulnerable to session Fixation attack. You can mitigate that using session regenerate_id as below
session_regenerate_id();
I will add it at your php script
3.) Session hijacking can only be prevented by ensuring that your site runs under https and not just http
4.) You are passing session username without sing htmlentities or htmlspecialchars functions.
Remember to do that when displaying session username on welcomepage.php
To answer your question, You can do that with Jquery/Ajax.
In the code below, am submitting your form using signin id attributes as can be seen in the jquery/ajax code below.
The code below displays all the actions triggered by the ajax/jquerycode
<div id="loader"></div>
<div id="result"></div>
Remember to include jquery.min.js files to ensure that it works
so here is your login.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username==""){
alert('please Enter username');
}
else if(password==""){
alert('please Enter password');
}
else{
$('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');
var datasend = "username="+ username + "&password=" + password;
$.ajax({
type:'POST',
url:'login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//empty username and password box after submission
$('#username').val('');
$('#password').val('');
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
}
});
}
})
});
</script>
<form action="" method="POST">
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="pwd"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input id="RememberMe" name="rememberme" type="checkbox" />
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<div id="loader"></div>
<div id="result"></div>
<div id="fadeoutResult"></div>
<button type="submit" class="btn btn-primary hidden-xs" id="signin">
Sign In
</button>
<button
type="submit"
class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
id="signin1"
>
Sign In
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
</form>
login.php
<?php
include("php_functions/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
//prevent session fixation attack
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("location: .php");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
echo '<script type="text/javascript">',
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
echo '}, 100);</script>';
}
}
?>
Finally, in case if the form does not get submitted, you can remove just tis two the form elements
<form> </form> and it will work
Updated section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username==""){
alert('please Enter username');
}
else if(password==""){
alert('please Enter password');
}
else{
$('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');
var datasend = "username="+ username + "&password=" + password;
$.ajax({
type:'POST',
url:'login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//empty username and password box after submission
$('#username').val('');
$('#password').val('');
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
$('#fadeoutResult').delay(5000).fadeOut('slow');
}
});
}
})
});
</script>
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="password"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input id="RememberMe" name="rememberme" type="checkbox" />
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<div id="loader"></div>
<div id="result"></div>
<div id="fadeoutResult"></div>
<button type="submit" class="btn btn-primary hidden-xs" id="signin">
Sign In Now
</button>
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
login.php
<?php
/*
//testing post data....
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = $_POST['username'];
echo $mypassword = $_POST['password'];
}
*/
include("php_functions/config.php");
session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);
//$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
//prevent session fixation attack
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("location: welcome.php");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
echo '<script type="text/javascript">',
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
echo '}, 100);</script>';
}
}
?>
There are many ways to collect data from a form, in my opinion the most practical is to use FormData. And the way to communicate javascript with php code is to use ajax. Please look at the following example.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<form action="" method="POST" name="index-login" id="index-login">
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="pwd"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input
id="RememberMe"
name="rememberme"
type="checkbox"
/>
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<button
type="submit"
class="btn btn-primary hidden-xs"
id="signin"
>
Sign In
</button>
<button
type="submit"
class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
id="signin1"
>
Sign In
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
</form>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js)
// You can access a form by its name,
// for example if the form had the name 'form' you could access it through
// `const form = document.forms.form`
// in your case by using the same name id value should be accessed thus
const indexLogin = document.forms["index-login"];
indexLogin.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
// Prevent submit form
event.preventDefault();
// Get data from inputs. Here this refer to the current form
const formData = new FormData(this);
// Inspect data collected
// for (const [key, value] of formData.entries()) {
// console.log(key, value);
// }
// Send form to php file
fetch("file.php", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(json => {
// do something
})
.catch(error => console.error(error.message));
}
But, your data will be visible through devtool in the network panel. I guess that will require another question.
I hope I have interpreted your question properly.

ajax error checkUsn is not defined at HTMLInputElement.onkeyup

I am doing login form connected to a mysql database and I want to check if username is existing inside database without reloading the whole page. I am using Ajax for sending and receiving data from the server. Now I'm stuck with this error can
"checkUsn is not defined at HTMLInputElement.onkeyup". can someone help me with this? i've tried to google it but it seems my code is correct.
Here is my code
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
$('#status').html(response);
if (response == "OK"){
return: true;
}else{
return false;
}
}
});
}else{
$('#status').html("INCORRECT USN AND PW");
return false;
}
}
checkdata.php
<?php
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if(isset($_POST['emp_username'])){
$usn = $_POST['emp_username'];
$checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0){
echo "OK";
}else{
echo "Your Username not exist";
}
exit();
}
?>
here is my form
<form class="modal-content animate" action="/login_action.php" method="post" onsubmit="return checkall();">
<div class="container">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"></div>
<img class="avatar img-responsive col-lg-6 col-md-6 col-sm-6 col-xs-6" src="img/employee_avatar.png" alt="Avatar">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"></div>
</div>
<div class="container">
<label for="usn"><b>Username</b></label>
<input id="usn" type="text" placeholder="Enter Username" name="usn" onkeyup="checkUsn();" required>
<label for="pw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pw" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
<button type="button" onclick="btnClickTest()"> test </button>
<span id="status"> </span>
</form>
Thank you in Advance!
Hi guys I just got typo error on my code I write
return: true;
instead of
return true;
now my code is now working smoothly.
thanks
Try to change you success function like this :
success: function(response){
$('#status').html(response);
if (response == "succeed"){
return: true;
}else{
return false;
}
}

without alert message how to display the error message in below text filed in a form

How to display the error message in below text field, below shown script and form without alert message?
script
success: function (data)
{
scrollDown();
var message = $("#messagee").val();
if(message == "" || message == null){
alert("enter a message");
}
else {
$('#chat_log').append('<div class="row msg_container base_receive"><div class="col-md-12 col-xs-12"><div class="messages msg_receive"><p><a>' + message + '</a></p></div></div></div>');
$('#messagee').val('');
}
},
form
<form class="form-horizontal msg_fixed_bottom send_message_form" id="data_form" method="POST" role="form" action="#" onsubmit="return validation();">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." value="<?php echo set_value('messagee'); ?>" />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit" name="submit">Send</button>
</span>
</div>
You can add a hidden div after the input and show it only if you have errors.
html :
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." value="<?php echo set_value('messagee'); ?>" />
<div id="errors" style="display:none;"></div>
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit" name="submit">Send</button>
</span>
</div>
js :
success: function (data)
{
scrollDown();
var message = $("#messagee").val();
if(message == "" || message == null){
$("#errors").html("enter a message");
$("#errors").fadeIn();
}
else {
$('#chat_log').append('<div class="row msg_container base_receive"><div class="col-md-12 col-xs-12"><div class="messages msg_receive"><p><a>' + message + '</a></p></div></div></div>');
$('#messagee').val('');
}
},
don't forget to hide and empty the div at the beginning of your validation() function (Before the Ajax call):
function validation() {
$("#errors").fadeOut();
$("#errors").html("");
$.ajax({
...
})
}
form
<form class="form-horizontal msg_fixed_bottom send_message_form" id="data_form" method="POST" role="form" action="#" onsubmit="return validation();">
<div class="panel-footer" id="myForm" >
<div class="input-group submit_group">
<input id="messagee" name="messagee" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." value="<?php echo set_value('messagee'); ?>" />
<span id='error_msg' class="yourcssclass"></span>
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit" name="submit">Send</button>
</span>
</div>
js
success: function (data)
{
scrollDown();
var message = $("#messagee").val();
if(message == "" || message == null){
document.getElementById('error_msg').innerHTML='enter a message';
}
else {
$('#chat_log').append('<div class="row msg_container base_receive"><div class="col-md-12 col-xs-12"><div class="messages msg_receive"><p><a>' + message + '</a></p></div></div></div>');
$('#messagee').val('');
}
},
Replace your line with this:
<input type="text" name="uname" value="<?php echo set_value('uname'); ?>" /><div id="infoMessage"><?php echo form_error('uname'); ?></div></br>
And change the variables names so they match with your variables names.
Read the CI documentation for more informations.

javascript - stop refresh if error is returned from php

I was wondering whether it would be possible to add something to my javascript which would allow a refresh if the form is submitted fine however will not refresh the page if an error is returned back from PHP.
is this possible? if so could anyone provide me with any guidance that will help me achieve this please. I have manage to get the javascript to refresh when the form is submitted and a message is returned.
this is the js:
function addCall() {
var data = $('#addForm').serialize();
$.post('../Admin/ManageCourses_AddSubmit.php', data, function(response){
$("#addForm").html(response);
//'soft'reload parent page, after a delay to show message
setTimeout(function(){
$('#addModal').modal('hide')
location.reload();
},3500);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
and the php which processes the form and validates it:
<?php
session_start();
if (empty($_POST['course_title'])) {
$message = " Value is required";
}
else {
$course_title = trim($_POST['course_title']);
# Validate Course #
if (!ctype_alpha($course_title)) {
$message = '<p class="error">Course title should be alpha characters only.</p>';
}
elseif (strlen($course_title) < 3 OR strlen($course_title) > 50) {
$message = '<p class="error">Course title should be within 3-50 characters long.</p>';
}
else {
include "../includes/db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $db_conx->prepare("INSERT INTO `insights`.`course_details` (`course_title`) VALUES (:course_title)");
$sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
$sql->execute();
$message = "<p class='text-success'> Record Successfully Added <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e) {
if( $e->getCode() == 23000)
{
$message = 'Course already exists in database';
}
else
{
$message = $e->getMessage();
}
}
}
}
die($message);
?>
It would really useful to the user to be able to make amendments to the form instead of rewriting it all again.
the form:
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add New Record: </h4>
</div>
<div class="modal-body">
<form id="addForm" class="addForm">
<div class="form-group">
<label class="control-label" for="forename">Forename:</label>
<div class="controls">
<input id="forename" name="forename" type="text" placeholder="Enter forename(s)" class="form-control" maxlength="100" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="surname">Surname:</label>
<div class="controls">
<input id="surname" name="surname" type="text" placeholder="Enter surname" class="form-control" maxlength="100" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="control-label" for="email">Email:</label>
<div class="controls">
<input id="email" name="email" type="email" placeholder="Enter a valid email" class="form-control" maxlength="255" value="" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="username">Username:</label>
<div class="controls">
<input id="username" name="username" type="text" placeholder="username" class="form-control" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="password">Password:</label>
<div class="controls">
<input id="password" name="password" type="password" placeholder="password" class="form-control" maxlength="40" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="confirm_password">Confirm Password:</label>
<div class="controls">
<input id="confirm_password" name="confirm_password" type="password" placeholder="retype password" class="form-control" maxlength="40" required="">
</div>
</div>
<?php
include "../includes/db_conx.php";
try {
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt2 = $db_conx->prepare('SELECT * FROM role_type');
$stmt2->execute();
$roles = $stmt2->fetchAll(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
die ("Could not connect to the database $mysql_dbname :" . $e->getMessage());
}
?>
<div class="control-group">
<label class="control-label" for="role_type">Select User Type:</label><p></p>
<select name="role">
<option value=''>Select One</option>";
<?php foreach($roles as $role): ?>
<option value="<?php echo $role['role_type_code'] ?>"><?php echo $role['role_title'] ?></option>
<?php endforeach ?>
</select>
</div>
<p></p>
<?php
include "../includes/db_conx.php";
try {
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt3 = $db_conx->prepare('SELECT * FROM course_details ORDER BY course_title');
$stmt3->execute();
$courses = $stmt3->fetchAll(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
die ("Could not connect to the database $mysql_dbname :" . $e->getMessage());
}
?>
<div class="control-group">
<label class="control-label" for="course_details">Select Course:</label><p></p>
<select name="course">
<option value=''>Select One</option>";
<?php foreach($courses as $course): ?>
<option value="<?php echo $course['course_code'] ?>"><?php echo $course['course_title'] ?></option>
<?php endforeach ?>
</select>
</div>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
</form>
</div>
<div class="modal-footer">
<div class="btn-toolbar">
<button type="button" class="btn btn-default" class="pull-right" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" class="pull-right" onclick="addUCall();">Submit <span class="glyphicon glyphicon-saved"></button>
</div>
</div>
</div>
</div>
</div>
Thank you in advance.
Your message variable contain both error and success message. It will reload page every time when it receives response.
Add this after $("#addForm").html(response); -
var n = response.search("class=\'text-success\'");
if(n!=-1){
//reload success
}
else{
//stay on page, errors
}
As you're returning the error messages in the response, check for the error class and do the reload if necessary.
$.post('../Admin/ManageCourses_AddSubmit.php', data, function(response){
if(response.contains("text-success")) {
// put your logic here for success
} else {
// logic for errors
}
});

Categories

Resources