I'm trying to process a form in PHP, however I don't want the page to refresh when the submit button is pressed. Instead I want to check if the email and password is correct; then either log the user in or display an error message (login_error in the example).
All of the code snippets below are in the same file, my question is how do I call a php function using AJAX to process the form in the same file?
Form:
<!-- Model dialog for login button -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" role="form" id="login_form" action="index.php" method="POST">
<div class="modal-header">
<h4>Login</h4>
</div>
<div class="modal-body">
<div class="form-group" id="login_error">
<label for="login-username" class="col-sm-2 control-label"></label>
<div class="col-sm-10" style="color: red;">
Oops! Your username or password is incorrect, please try again!
</div>
</div>
<div class="form-group">
<label for="login-username" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input required type="text" class="form-control" name="login-email" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="login-password" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input required type="password" class="form-control" name="login-password" placeholder="Password">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" href = "#register" data-toggle="modal" formnovalidate>Register</button>
<button type="submit" class="btn btn-success" name="login_submit" id="login_submit">Login</button>
</div>
</form>
</div>
</div>
</div>
PHP I want to call:
<?php
if (isset($_POST["login_submit"])) {
$email = $_POST["login-email"];
$password = $_POST["login-password"];
if (login($email, $password)) {
die("<script>location.href = 'LoginSystem/cookiecontrol.php?action=set&email=$email'</script>"); // Set the cookie
} else {
echo "<script>$('#login_error').show();</script>";
}
}
?>
JQuery:
<script>
$("#login_error").hide();
$("#login_submit").click(function (e) {
e.preventDefault();
$.ajax({url: '/PHP%20Files/Computing%20Project%20-%20Website/ICTeacher/LoginSystem/wrongpassword.php',
data: {action: 'index.php'},
type: 'post',
success: function (output) {
alert(output);
}
});
});
</script>
To process the php code via an ajax request in the same page is fairly straightforward but you have to ensure that you only return the data you want rather than the entire page which could easily happen.
To do that use ob_clean to discard the output buffer to that current point in the script and then ensure you exit after sending the data.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST["login_submit"] ) ) {
ob_clean();/* discard any output there may have been so far in the document */
$email = $_POST["login-email"];
$password = $_POST["login-password"];
if ( login( $email, $password ) ) {
die("<script>location.href = 'LoginSystem/cookiecontrol.php?action=set&email=$email'</script>"); // Set the cookie
} else {
echo "<script>$('#login_error').show();</script>";
}
/* the ajax request should only process to this point */
exit();
}
?>
Related
I am looking to process data in popup as ajax and display successful message inside popup only, Nothing is happening when I click on 'Submit An Offer' button, in console logs I saw uncaught error.
Popup Modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal<?php echo esc_html($post->ID);?>" data-whatever="#getbootstrap">Submit Offer</button>
<div class="modal fade" id="exampleModal<?php echo esc_html($post->ID);?>" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Submit Your Offer for <?php echo esc_html($post->post_title);?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p class="statusMsg"></p>
<form role="form">
<div class="form-group row">
<label class="col-md-12" for="Name"><?php esc_html_e( 'Name', 'ivproperty' ); ?><span class="red-star">*</span></label>
<input class="col-md-12" id="name" name="name" type="text" required>
<imput type="hidden" id="id" value="<?php $post->ID ?>">
</div>
<div class="form-group row">
<label for="email" class="col-md-12"><?php esc_html_e( 'Email', 'ivproperty' ); ?><span class="red-star">*</span></label>
<input class="col-md-12" id="email" type="text" required>
</div>
<div class="form-group row">
<label for="price" class="col-md-12"><?php esc_html_e( 'Price', 'ivproperty' ); ?><span class="red-star">*</span></label>
<input class="col-md-12" id="price" type="number" required>
</div>
<div class="form-group row">
<label for="purchase_type" class="col-md-12"><?php esc_html_e( 'Purchase Type', 'ivproperty' ); ?><span class="red-star">*</span></label>
<select class="col-md-12" id="purchase_type" required>
<option disabled selected value> -- select an option -- </option>
<option value="Cash">Cash</option>
<option value="Conventional Loan">Conventional Loan</option>
<option value="FHA Loan">FHA Loan</option>
<option value="MSHDA Conventional Loan">MSHDA Conventional Loan</option>
<option value="MSHDA FHA Loan">MSHDA FHA Loan</option>
<option value="Land Contract">Land Contract</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">Submit An Offer</button>
</div>
</form>
</div>
<div class="modal-footer">
<?php echo esc_html($post->ID);?>
</div>
</div>
</div>
</div>
Script:
<script>
function submitContactForm(){
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#name').val();
var email = $('#email').val();
var price = $('#price').val();
var purchase_type = $('#purchase_type').val();
var id = $('#id').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#inputName').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'<?php get_template_directory_uri(); ?>/submitoffer.php',
data:'OfferSubmit=1&name='+name+'&email='+email+'&price='+price+'&purchase_type='+purchase_type+'&id='+id,
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
if(msg == 'ok'){
$('#name').val('');
$('#email').val('');
$('#price').val('');
$('#purchase_type').val('');
$('.statusMsg').html('<span style="color:green;">Offer Submitted Successfully.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Error I'm seeing in console log:
What I want is when user open's popup and fill the form and then submit it, data should get processed inside popup only and display the status result.
This question doesn't answer my problem as pop-up modal stopped working after applying solution provided in a little similar question.
Try to put your function inside this:
$(function() {
// your code here
});
Or this:
(function( $ ) {
// your code here
} )( jQuery );
Can someone help, I cant seem to get the data colleted from the form to be sent to the mysql database.
I am very new to coding and I cant seem to figure out why the form data is not being sent to the mysql database table.
Please any help would be muchly appricated.
once I press submit the page closes than refreshs without any errors, but the data has not been sent to the database table.
Please see code below.
<?php include'inc/header.php'; ?>
<div class="container">
<center>
<h2 style="color: #odc16f">Shipped</h2>
<hr>
</center>
<center>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#addEmpModal">
Add Order
</button>
</center>
<!-- Modal -->
<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="" method="post">
<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" id="myModalLabel">Add New Order</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter Name</label>
<input class="form-control" type="text" name="customer" id="customer" placeholder="Enter Name">
<label id="lbcustomer" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter Date</label>
<input class="form-control" type="date" name="date" id="date" placeholder="Enter Date">
<label id="lbdate" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter Invoice</label>
<input class="form-control" type="number" name="invoice" id="invoice" placeholder="Enter Invoice">
<label id="lbinvoice" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter eBay</label>
<input class="form-control" type="number" name="ebay" id="ebay" placeholder="Enter eBay">
<label id="lbebay" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter Shipped</label>
<input class="form-control" type="text" name="shipper" id="shipper" placeholder="Enter Shipped">
<label id="lbshipper" style="color:red"></label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="save">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div><!-- /.container ends here -->
<?php
include'inc/footer.php';
?>
<script>
$(document).ready(function() {
$(document).on('click', '#save', function() {
var customer = $("#customer").val();
var date = $("#date").val();
var invoice = $("#invoice").val();
var ebay = $("#ebay").val();
var shipper = $("#shipper").val();
if (customer == "") {
$("#lbcustomer").html("Enter Name");
} else if (date == "") {
$("#lbdate").html("Enter Date");
} else if (invoice == "") {
$("#lbinvoice").html("Enter Invoice");
} else if (ebay == "") {
$("#lbebay").html("Enter eBay");
} else if (shipper == "") {
$("#lbshipper").html("Enter Shipper");
} else {
$.ajax({
url: "save_data.php",
type: "post",
data: {
customer: customer,
date: date,
invoice: invoice,
ebay: ebay,
shipper: shipper
},
success: function(data) {
alert("Order Has Been Successful");
$("#addEmpModal").modal('hide');
location.reload();
}
});
}
});
});
</script>
Please see below the save_data.php code
<$php
include 'config/config.php';
global $con;
$customer = $_POST['customer'];
$date = $_POST['date'];
$invoice = $_POST['invoice'];
$ebay = $_POST['ebay'];
$shipper = $_POST['shipper'];
$save_data = "INSERT INTO orders(customer, date, invoice, ebay, shipper)VALUES('$customer','$date','$invoice','$ebay','$shipper')";
$result = mysqli_query($con, $save_data);
and below is the config.php code.
<?php
$con = mysqli_connect("localhost","root","Password","shippedorders");
if (!$con) {
echo "Failed to connect to MySQL: ".mysqli_connect_error($con);
}
you are missing
action in :
<form action="save_data.php" method="post">
or are you running your php in same page as html ? or you
I'm new to modals, i want to submit a form and then show success popup if user form is validated else want to show error popup. Also my it should execute php file for sending the email to user in background.
So, far i'm successful in executing the php file in background and show the model when user clicks on submit button.
But i want the popup to show when the form is validated. Also i want to use type="submit" instead of type="button" for form submit.
Here's my code :
<!-- javascript code to execute php file -->
<script type="text/javascript">
function executePhp() {
$.post("sendmail.php");
return false;
}
</script>
<!-- javascript code ends -->
<form class="well" action="" method="">
<div class="form-group col-md-6">
<label for="inputPassword4">Full Name</label>
<input type="text" name="name" class="form-control" id="inputPassword4" placeholder="Enter Full Name">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Phone Number</label>
<input type="number" name="mobile" class="form-control" id="inputEmail4" placeholder="Enter Mobile Number">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Email</label>
<input type="email" name="email" class="form-control" id="inputPassword4" placeholder="Enter Your Email">
</div>
</div>
<button type="button" class="btn btn-primary" onclick="executePhp()" style="margin-left: 3%;"
data-toggle="modal" data-target="#myModal">Check</button>
</form>
<!-- Code for popup -->
<!-- Modal -->
<div class="modal fade mymodal" id="myModal" role="dialog">
<div class="modal-dialog mydialog">
<!-- Modal content-->
<div class="modal-content mycontent">
<div class="modal-header myheader">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Message</h3>
</div>
<div class="modal-body mybody">
<br>
<br>
<h3>Thanks for choosing</h3>
<h4>
Your details will arive by email.
Sit back, we'll get back to you soon.
</h4>
<br>
<br>
</div>
<div class="modal-footer myfooter">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Code for popup end-->
Thank you.
You can use Jquery to achieve this.
In you php you can have two variables before the validation like:
$popup_message = "";
$popup_message_color = "";
Now if the form is validated you can display the modal like this:
$popup_message = "login successfully.";
$popup_message_color = "success";
//Open Modal
echo "<script type='text/javascript'>
$(document).ready(function(){
$('#myModal').modal('show');
});
</script>";
In the modal body you can display the message and color.
<div class="modal-body">
<p class="text-<?php echo $popup_message_color; ?>"><?php echo $popup_message; ?></p>
</div>
The same would be done for if validation fails, just change your message and color to $popup_message_color = "danger";
Note If you are validation to another page then the modal should be in that page and you change the close buttons to a link to go back.
Also php script should come after you loaded the jquery.
I'm making a login system using modal dialog from bootstrap 3 and im adding a function to keep the user logged in if they check the checkbox in the modal dialog.
I want to keep a user logged in, even he/she refreshes or closes the browser.
index.php
<div class="container" id="myLogin">
<div class="row">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h5 class="modal-title">PLEASE ENTER YOUR EMAIL ADDRESS AND PASSWORD TO LOG IN.</h5>
</div>
<div class="modal-body">
<div id="show" class="lalert lalert-warning"></div>
<div class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
<input type="text" name="lemail" id="lemail" value="<?php echo $unm ?>" class="form-control" placeholder="Enter Email Address..." />
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
<input type="password" name="lpassword" id="lpassword" value="<?php echo $pwd ?>" class="form-control" placeholder="Enter Password..." />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="checkbox" name="chkbox" value="staylogged" class="checkbox-inline" />
<label> Keep me logged in</label> <b>|</b>
Forgot your password?
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" id="login" name="login" class="btn btn-primary"><span class="glyphicon glyphicon-user"></span> Login</button>
<button type="button" class="btn btn-info show-page modal-btn" data-page="Signup" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-list-alt"></span> Register</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
script:
jQuery(function () {
$("#lemail").val($.cookie("unm"));
$("#lpassword").val($.cookie("pwd"));
});
$("#email").val($.cookie("unm") || "");
$("#lpassword").val($.cookie("pwd") || "");
php:
<?php
session_start();
$unm = $_POST['lemail'];
$pwd = $_POST['lpassword'];
?>
In order to get session_start(); to work,
you need to add variables to the $_SESSION array. Change you PHP code to this:
<?php
//Start the session
session_start();
//ALWAYS check if a $_POST variable is set before using it.
if(isset($_POST['lemail'])){
$unm = $_POST['lemail'];
} else {
//Error Code Goes Here
}
if(isset($_POST['lpassword'])){
$pwd = $_POST['lpassword'];
} else {
//Error Code Goes Here
}
//Set SESSION vars
$_SESSION["unm"] = $unm;
$_SESSION["pwd"] = $pwd;
When you want to check if they are logged in, use this code
session_start();
if(isset($_SESSION["unm"]) && isset($_SESSION["pwd"])){
$loggedIn = true;
//At this point you can also check your database if they are actually a user for extra security
} else {
$loggedIn = false;
}
Please, make sure your cookies is going save or not.
And another thing is make sure of expire time.
set coockies in PHP, like :
setcookie(
'pageVisits', // Name of the cookie, required
$visited, // The value of the cookie
time()+7*24*60*60, // Expiration time, set for a week in the future
'/', // Folder path the cookie will be available for
'demo.tutorialzine.com' // Domain to which the cookie will be bound
);
And Read coockies in JS:
$(document).ready(function(){
// Getting the kittens cookie:
var str = $.cookie('pageVisits');
// str now contains the value of $visited
});
I've got an external js file with the following code in it that is checking to see if a person login credentials are true or false. When I put this jquery into the actual php file it will work as intended but when it I put the jQuery into the js file and try calling it it doesn't work and I'm not getting any errors. What's wrong with the call?
js file:
function handleLogin(event) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
username = $form.find( "input[name='username']" ).val(),
password = $form.find( "input[name='password']" ).val(),
url = "../process/login.php";
// Send the data using post
var posting = $.post( url, { username: username, password: password } );
// Reset data in #testStatus textarea
posting.done(function( data ) {
if (data == '1') {
$('#loginModal').modal('hide')
$( "#loginOption" ).replaceWith( "<li id='loginOption'><a href='logout.php'>Logout</a></li>" );
}
});
}
php file (the call of the function located at the end of the php file):
<!-- Modal -->
<div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="loginModalLabel">Login</h4>
</div>
<div class="modal-body">
<form id="loginForm" action="">
<div class="form-group">
<label for="username">Username</label>
<input name="username" type="text" class="form-control" id="username" placeholder="Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input name="password" type="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="loginSubmit" name="login" class="btn btn-primary" value="Login">
</div>
</form>
</div>
</div>
</div>
<script>
$("#loginForm").submit(function handleLogin() { });
</script>
You need to pass the function reference to the submit event handler...
Instead you are creating a new function which does not do anything to the submit handler, so try
$("#loginForm").submit(handleLogin);
It should be like this:
$("#loginForm").submit(function(e){
handleLogin(e);
});