Solution for ajax form submit - javascript

I have a registration form in bootstrap modal, I want to send it and validate to display errors without reloading the page (because the modal closes). Someone can tell me the solution? I tried much variations but still not working. Here is my code, working but not perfectly it sends but still reloads the page.
<div class="modal fade" id="myModal1">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Registration</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<form id="regform" method="post" action="#">
<?php include('errors.php') ?>
<div class="input-group">
<label>Username</label>
<input id="name" type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input id="email" type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>Password</label>
<input id="pass1" type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input id="pass2" type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
<p>
Already a member? Sign in
</p>
</form>
<script>
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password1 = $("#pass1").val();
var password2 = $("#pass2").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1=' + name + '&email1=' + email + '&password11=' + password1 + '&password22=' + password2;
if (name == '' || email == '' || password1 == '' || password2 == '') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "server.php",
data: dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
return false;
});
});
</script>
</div>
</div>
</div>
</div>

Related

Ajax form submission uncaught error when click on submit button

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 );

Cant get data from form sent to mysql database

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

All variables appear to not be POSTing

I am currently working on a website that takes information from a form in a Bootstrap modal (addStudentModal.php) and sends it to createRecord.php via a jQuery script (dataManageFunctions.js). When the data reaches createRecord.php, it gets inserted into a MySQL database. For debugging purposes, instead of executing the INSERT command, I just had it echo out the variables that were POSTed to it. I discovered that all but 2 fields are not getting posted and I have absolutely no idea why. Specifically, gYear and lName are echoing blank values. I've checked spelling and tried to ensure that the variable names and IDs are identical. Maybe I'm missing something, I don't know.
The files in question are below:
addStudentModal.php
<!-- ADD STUDENT Modal -->
<div class="modal fade" id="addStudentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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" id="myModalLabel">Add New Student</h4>
</div>
<div class="modal-body">
<div id="additionResults"></div>
<!-- EDIT form-->
<form role="form" action="" method="" id="addStudentForm">
<div class="form-group">
<label for="studentID">Student ID Number:</label>
<input type="text" class="form-control" name="studentID" id="studentID" placeholder="123456">
</div>
<div class="form-group">
<label for="lastName">Graduation Year:</label>
<input type="text" class="form-control" name="gradYear" id="gradYear" placeholder="0">
</div>
<div class="form-group">
<label for="lastName">Last Name:</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder="Doe">
</div>
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="John">
</div>
<div class="form-group">
<label for="serHrsToDate">Service Hours to Date:</label>
<input type="text" class="form-control" name="serHrsToDate" id="serHrsToDate" placeholder="0.00">
</div>
<div class="form-group">
<label for="internToDate">Internships to Date:</label>
<input type="text" class="form-control" name="internToDate" id="internToDate" placeholder="0">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" name="save" value="save"> Add Student </button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<!-- END ADD STUDENT MODAL -->
dataManageFunctions.js - only relevant snippet is copied
// JS for Add Student
$(function() {
$("#addStudentForm").bind('submit',function() {
var sID = $('#studentID').val();
var gYear = $('#gradYear').val();
var lName = $('#lastName').val();
var fName = $('#firstName').val();
var servHrs = $('#serHrsToDate').val();
var interns = $('#internToDate').val();
$.post('assetScripts/editInfo/createRecord.php',{sID:sID, gYear:gYear, lName:lName, fName:fName, servHrs:servHrs, interns:interns}, function(data){
$("#additionResults").html(data);
});
return false;
});
});
createRecord.php
<?php
include("../../config/db-connect.php");
$errExist = false;
if(isset($_POST['sID'])){
$safeID = intval($_POST['sID']);
if(!preg_match("/^.*(?=.{6,})(?=.*[0-9]).*$/", $safeID)){
$errExist = true;
}
} else {
$errExist = true;
}
if(isset($_POST['gYear'])){
$safeYear = intval($_POST['gYear']);
if(!preg_match("/^.*(?=.{4,})(?=.*[0-9]).*$/", $safeYear)){
$errExist = true;
}
} else {
$errExist = true;
}
if(isset($_POST['lName'])){
$safeLastName = mysql_real_escape_string(filter_var($_POST['lName'], FILTER_SANITIZE_STRING));
} else {
$errExist = true;
}
if(isset($_POST['fName'])){
$safeFirstName = mysql_real_escape_string(filter_var($_POST['fName'], FILTER_SANITIZE_STRING));
} else {
$errExist = true;
}
if(isset($_POST['servHrs'])){
$safeHrs = floatval($_POST['servHrs']);
} else {
$errExist = true;
}
if(isset($_POST['interns'])){
$safeInterns = intval($_POST['interns']);
} else {
$errExist = true;
}
// check if an error existed when checking inputs
if(!$errExist){
echo '<div class="alert alert-success" role="alert"><strong>Success!</strong></div>';
echo $_POST['sID'].', '.$_POST['gYear'].', '.$_POST['lName'].', '.$_POST['fName'].', '.$_POST['servHrs'].', '.$_POST['interns'].'<br>';
echo $safeID.', '.$safeYear.', '.$safeLastName.', '.$safeFirstName.', '.$safeHrs.', '.$safeInterns.'<br>';
echo $errExist.'<br>';
} else {
echo '<div class="alert alert-danger" role="alert"><strong>Failure!</strong></div>';
echo $_POST['sID'].', '.$_POST['gYear'].', '.$_POST['lName'].', '.$_POST['fName'].', '.$_POST['servHrs'].', '.$_POST['interns'].'<br>';
echo $safeID.', '.$safeYear.', '.$safeLastName.', '.$safeFirstName.', '.$safeHrs.', '.$safeInterns.'<br>';
echo $errExist.'<br>';
}
?>
It's also worth noting that I also had it echo isset(variable name) which returned 1 (true) for every variable. And yes, I ensured that the values I entered to test followed every condition so $errExist shouldn't have been set true.

Modal Hide Not Working

The modal form submits, returns formSuccess, sends the email, returns the signup alert, but the modal does not hide. Any suggestions?
The modal html:
<div class="modal fade" id="signupModal" tabindex="-1" role="dialog" aria-labelledby="signupModal" 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">Provide a few details and we'll be in touch...</h4>
</div>
<div class="modal-body">
<form id="contactForm" role="form">
<input type="hidden" id="theme" name="theme" value="flatly"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Your name" required>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Your email address" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Have a question or comment?" required></textarea>
</div>
</div>
<div class="modal-footer">
<button id="form-submit" type="submit" class="btn btn-success">Sign Up</button>
</div>
</form> <!-- add tag v_07 -->
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
The signup alerts html:
<div class="container form-message">
<div class="row">
<div id="signupSuccess" class="alert alert-success" style="display:none">
<p id="signupSuccessText">Thanks for signing up for preview access, we'll be in touch! In the meantime join us on Twitter, Facebook, and LinkedIn.</p>
</div>
<div id="signupError" class="alert alert-info" style="display:none">
<p id="signupErrorText">Well this is embarrassing. It looks like we're having trouble. While we fix this, we can be reached at info#timbercheck.net</p>
</div>
</div>
</div>
And here is the code from js file.
$("#contactForm").submit(function(event){
event.preventDefault();
submitForm();
});
function submitForm(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
}
}
});
};
function formSuccess(){
$("#signupSuccess").show();
$("#signupModal").modal('hide'); // add v_07
};
function formError(){
$("#signupError").show();
$("#signupModal").modal('hide'); // add v_07
};
You should add data-dismiss="modal" instead on your button because you are anyway going to show another modal.
EDIT : Change type from submit to button
<button id="form-submit" type="button" class="btn btn-success" data-dismiss="modal">Sign Up</button>
And try this,
$("#form-submit").click(function(event){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
}
}
});
};
function formSuccess(){
$("#signupSuccess").show();
$("#signupModal").modal('hide'); // add v_07
};
function formError(){
$("#signupError").show();
$("#signupModal").modal('hide'); // add v_07
};
Instead of..
$('#myModal').modal('hide')
This worked...
$('#myModal').hide();
$('.modal-backdrop').hide();
Source: https://stackoverflow.com/a/29560331/7069248
Could be related to version of Bootstrap
This solution works for me:
setTimeout(function(){
$('#close-modal').click();
$('#close-modal').click();
},200);

Calling a user defined PHP functions using AJAX in the same file

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();
}
?>

Categories