AJAX POST in same window instead of new - javascript

I tried to make a contact form within a bootstrap modal.
An alert should show up right after submitting the form in the modal.
It is working fine on my site which I use for testing.
But when I integrate the code in my main site the alert is shown as text in a new window. Same code. Different response. What could cause this behavior?
HTML:
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_name">Name</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_email">Email</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-->
PHP:
<?php
// configure
$from = 'noreplay#xy.de';
$sendTo = 'webmaster#xy.de';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});

The action parameter in form tag action="contact.php" is forcing the page to refresh try using this as form tag :-
<form id="contact-form">
and change $(this).serialize() in your ajax post code to :-
$('#contact-form').serialize()

Related

After submitting form its showing success message on different page

After clicking the submit now button I can't get the message above the form. Please help me out in this. Please anyone.
Here is index.html form:
<form id="contact-form" method="post" action="contact.php">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_need">Please specify your need *</label>
<select id="form_need" name="need" class="form-control" required="required" data-error="Please specify your need.">
<option value="">-----</option>
<option value="Request quotation">Request quotation</option>
<option value="Request order status">Request order status</option>
<option value="Request copy of an invoice">Request copy of an invoice</option>
<option value="Other">Other</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please, leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LdX5uQUAAAAAEPAP03K3_jafzIdoOFSblSgm2um" data-callback="verifyRecaptchaCallback" data-expired-callback="expiredRecaptchaCallback"></div>
<input class="form-control d-none" data-recaptcha="true" required data-error="Please complete the Captcha">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-success btn-send btn-danger-gradiant mt-3 mb-3 text-white border-0 py-2 px-3" value="Send message"><span> SUBMIT NOW <i class="fa fa-paper-plane"></i></span></button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted">
<strong>*</strong> These fields are required.
</p>
</div>
</div>
</div>
</form>
This is the contactus.js:
$(function () {
window.verifyRecaptchaCallback = function (response) {
$('input[data-recaptcha]').val(response).trigger('change');
}
window.expiredRecaptchaCallback = function () {
$('input[data-recaptcha]').val("").trigger('change');
}
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
This is the contact.php form:
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'Demo contact form <demo#domain.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <demo#domain.com>';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
// ReCaptch Secret
$recaptchaSecret = '6LdX5uQUAAAAAEakfeeS4jlKkOjvSaqrawNp4gUD';
// let's do the sending
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try {
if (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}
Your message is on the an another page because you use action="contact.php".
Try to remove that part of code.Also remove the portion with form
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<button type="submit" class="btn btn-success btn-send btn-danger-gradiant mt-3 mb-3 text-white border-0 py-2 px-3" onclick="addYourFunctionhere()" value="Send message"><span> SUBMIT NOW <i class="fa fa-paper-plane"></i></span></button>
<script>
function addYourFunctionhere(){
var getform_name= $("#form_name").val()
//and here use ajax to send the var from top
$.ajax({
type: "POST",
url: url,
data: {"username":getform_name},
success: function (data) {
console.log(data);
}
});
}
</script>

How do I creat a jquery form validator

I am trying to create a dynamic website using php. The site is uploaded to a free domain this is my first real world project so I want to put in as best as I can. I created a modal, in it there is a form and I want this from to validate and without refreshing the page. but I don't know why my mail() is not working please can someone tell me what I am doing wrong.
This is my fixed form inside the modal:
<div class="modal fade" id="myModal" tabindex="-1" role="form" aria-labelledby="#modalLabel">
<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>
<h3 class="modal-title " id="modalLabel">Send
<?php echo
$brandName; ?> a message</h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="thumbnail">
<form action="contact_process.php" method="POST" role="form" autocomplete="off" class="form-container">
<small>
<i class="text-center
text-danger">all fields are required</i>
</small>
<div class="form-group has-danger">
<label class="sr-only" for="name">Name
</label>
<input type="text" name="name" placeholder="Your Name" class="form-control" id="mail-name" tabindex="1">
</div>
<div class="form-group has-danger">
<label class="sr-only" for="email">Email
</label>
<input type="email" name="email" placeholder="Your E-mail" class="form-control" id="mail-email" tabindex="2">
</div>
<div class="form-group has-danger">
<label for="tel" class="sr-only">Tell
no.
</label>
<input type="text" name="phone" placeholder="Your Phone Number" class="form-control" id="mail-
phone" tabindex="3">
</div>
<div class="form-group has-danger">
<label for="message" class="sr-only">
</label>
<textarea class="form-control
form-textarea" placeholder="Message" rows="5" spellcheck="true" name="message" id="mail-message" tabindex="4"></textarea>
</div>
<input type="button" class="btn
btn-danger" data-dismiss="modal" aria-label="Close" value="Cancel" tabindex="5">
<input id="mail-submit" type="submit" class="btn btn-primary" value="Send Message" name="submit" data- submit="...Sending" tabindex="6">
<p class="form-msg"></p>
</form>
</div>
<!--END thumbnail-->
</div>
<!--END col-->
</div>
<!--END row-->
</div>
<!--modal-body-->
</div>
<!--modal-content-->
</div>
<!--modal-dialog-->
</div>
<!---modal-->
This is the php form validation in my includes folder:
<pre>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmail = false;
$errorPhone = false;
if (empty($name) || empty($email) || empty($phone) || empty($message)) {
echo "<span class='err'>Fill in all fields!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='err'>Invalid email please make sure you enter a
valid email address!</span>";
$errorEmail = true;
}
elseif (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?
\d{3}[\s-]?\d{4}$/i",$phone)) {
echo "<span class='err'>Please enter only a valid phone number!
</span>";
$errorPhone = true;
}
else{
// add resipeants
$to = "danjumashiwaju#gmail.com";
// create subject
$subject = "$name sent you a message from www.djshumzy.com";
// construct a message
$msg = "Name: $name\r\n";
$msg .= "Email: $email\r\n";
$msg .= "Tell: $phone\r\n";
$msg .= "Message: \r\n$message";
$msg = wordwrap($meg, 70);
//set mail header
$headers = "MINE-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=1so-8859-1\r\n";
$headers .= "From: $name <$email>\r\n";
$headers .= "X-priority: 1\r\n";
$headers .= "X-MSMail-priority: High1\r\n\r\n";
mail( $to, $subject, $msg, $headers);
} if (mail === 1) {
echo "<span class='suc'>Thank You!...Your Message has been Sent !
</span>";
}
}
?>
<script>
$("#mail-name, #mail-email, #mail-phone,
#mail-message").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
var errorPhone = "<?php echo $errorPhone; ?>";
if (errorEmpty == true) {
$("#mail-name, #mail-email, #mail-phone,
#mail-message").addClass("input-error");
}
if (errorEmail == true) {
$("#mail-email").addClass("input-error");
}
if (errorPhone == true) {
$("#mail-phone").addClass("input-error");
}
if (errorEmpty == false && errorEmail == false && errorPhone == false) {
$("#mail-name, #mail-email, #mail-phone, #mail-message").val("");
}
</script>
</pre>
Here is my jquery validation(.js)
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-msg").load("includes/contact_process.php", {
name: name,
email: email,
phone: phone,
message: message,
submit: submit
});
});
});// END FORM VALIDATING
Please what do I have to do to make this from submit to emails and validate at the same time.
Thus the form validates but it does not send the email and just gives an error message instead.
Use https://jqueryvalidation.org/
$( "#myform" ).validate({
rules: {
field: {
required: true
},
email: {
required: true,
email: true
}
},
messages: {
field: "Please Enter Your Name",
email: "Please Enter Your Email Address"
}
});
<link href="https://jqueryvalidation.org/files/demo/site-demos.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="myform">
<label for="field">Enter Name : </label>
<input type="text" class="left" id="field" name="field">
<br/>
<label for="email">Email Address: </label>
<input type="text" id="email" name="email">
<br/>
<input type="submit" value="Validate!">
</form>
This jQuery plugin makes simple clientside form validation easy.

How to write success message of form in bootstrap modal?

SOLVED
Ok, I solved the problem with AJAX but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. The working code is by CodexWorld. I hope I help someone who is helpless.
I am searching for solution all day but I don't get relevant solution anywhere. Other similar questions here are old, maybe there are fresh solution.
So I am using Bootstrap the first time (files are on the themes of Wordpress). I started to build a contact form in Modal and if I hit submit the window closes, I get the e-mail, but the success-message only shows if I reopen it. I tried every solution I found on internet.
I am not familiar with javascript and jquery, I don't know how to use it.
In the footer I implemented:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
In index there is the form with Modal:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="form-horizontal clearfix" id="contact-form" name="contact" role="form" method="post" action="index.php">
<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">Küldj egy üzenetet</h4>
</div>
<div class="modal-body">
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Itt landol</label>
<div class="col-sm-10">
<input class="form-control" id="disabledInput" type="text" placeholder="hello#kanizsaipatricia.hu" disabled>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Név</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="Minta János" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="valaki#email.hu" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Üzenet</label>
<div class="col-sm-10">
<textarea class="form-control" placeholder="Ide írd az üzenetet" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
</div>
</div>
<?php echo $result; ?>
<div class="modal-footer">
<button type="button" class="btn btn-cancel hvr-fade" data-dismiss="modal">Mégsem</button>
<input type="submit" id="submit" name="submit" data-toggle="modal" data-target="#resultModal" value="Elküldöm" class="btn btn-info hvr-wobble-horizontal">
</div>
</pop:form>
</div>
</div>
The php code behind the form:
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Üzenetküldő űrlap';
$to = 'hello#kanizsaipatricia.hu';
$subject = 'Új üzenet formon keresztül';
$body = "Feladó: $name\n E-Mail: $email\n Üzenet:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Kérlek, add meg a neved!';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Nem érvényes e-mail cím!';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Nem írtál üzenetet.';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success noshadow">Elküldve.</div>';
} else {
$result='<div class="alert alert-danger noshadow">Sajnálom, hiba lépett fel az üzenet küldése közben. Próbáld újra!</div>';
}
}
}
I'm open minded for any solution in any language! Please help!
Ok, I solved the problem with ajax but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. Thanks to CodexWorld.
Bootstrap & jQuery Library
Bootstrap is used to create modal popup and design HTMl form, include the bootstrap and jQuery library first.
<!-- Latest minified bootstrap css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest minified bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Bootstrap Modal Popup Form
<!-- Button to trigger modal -->
<button class="btn btn-success btn-lg" data-toggle="modal" data-target="#modalForm">
Open Contact Form
</button>
<!-- Modal -->
<div class="modal fade" id="modalForm" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Contact Form</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<p class="statusMsg"></p>
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage">Message</label>
<textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
</div>
</div>
</div>
</div>
JavaScript Code: Validate and Submit Form
<script>
function submitContactForm(){
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').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 if(message.trim() == '' ){
alert('Please enter your message.');
$('#inputMessage').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'submit_form.php',
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
if(msg == 'ok'){
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Send Contact Request Email (submit_form.php)
<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
/*
* Send email to admin
*/
$to = 'admin#example.com';
$subject= 'Contact Request Submitted';
$htmlContent = '
<h4>Contact request has submitted at CodexWorld, details are given below.</h4>
<table cellspacing="0" style="width: 300px; height: 200px;">
<tr>
<th>Name:</th><td>'.$name.'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Email:</th><td>'.$email.'</td>
</tr>
<tr>
<th>Message:</th><td>'.$message.'</td>
</tr>
</table>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: CodexWorld<sender#example.com>' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}

Show Bootstrap's Alert on successful Submit

I'm trying to work on bootstrap's alert. Particulary this:
<div class="alert alert-success" role="alert">...</div>
I wanted it to pop-up on the modal after I successfully hit the submit button. How do I do that?
Here are my codes:
<!--____________________________ADD AGENT________________________-->
<div class="modal fade" id="addAgent" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<form role="form" action="php/addAgent.php" method="POST">
<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 Agent</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="fullname">Full Name</label>
<div class="row">
<div class="col-sm-4">
<input type="text" class="form-control" placeholder="First Name" name="fname">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" placeholder="Middle Name" name="mname">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" placeholder="Last Name" name="lname">
</div>
</div>
</div><!--___________FORM GROUP_____________-->
<div class="form-group">
<div class="row">
<div class="col-sm-4">
<label for="sel1">Type:</label>
<select class="form-control" name="agentType" id="sel1">
<option value="1">Broker</option>
<option value="2">Agent</option>
<option value="3">Sub-Agent</option>
</select>
</div>
<div class="col-sm-4">
<label for="sel1">Project:</label>
<select class="form-control" id="sel1">
<option>Mezza</option>
<option>Tivoli Gardens</option>
<option>Verawoods Residences</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<label for="email">Email Address</label>
<input type="email" class="form-control" name="email" id="email">
</div>
<div class="col-sm-4">
<label for="contact">Contact Number</label>
<input type="text" class="form-control" name="contact" id="contact">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-12">
<label for="homeAdd">Home Address</label>
<input type="text" class="form-control" name="homeAdd" id="homeAdd">
</div>
</div>
</div>
</form>
</div>
</div> </div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="submit"/>
<button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>
</div>
</div>
</div>
</div><!--______________________ADD AGENTS MODAL_______________________-->
<!-- Button trigger modal -->
Here's my PHP:
<?php
$user="root"; $pass=""; $db="realesate";
$db = new mysqli('localhost', $user, $pass, $db);
//check connection
if ( $db->connect_error) {
die('Connect Error: ' . $db->connect_errno . ': ' . $db->connect_error );
}
//insert data
$sql = "insert into agent (AgentFName , AgentMName , AgentLName , AgentContact , AgentEmail, AgentAddress , agentType)
values (
'{$db->real_escape_string($_POST['fname'])}' ,
'{$db->real_escape_string($_POST['mname'])}' ,
'{$db->real_escape_string($_POST['lname'])}' ,
'{$db->real_escape_string($_POST['contact'])}' ,
'{$db->real_escape_string($_POST['email'])}' ,
'{$db->real_escape_string($_POST['homeAdd'])}' ,
'{$db->real_escape_string($_POST['agentType'])}')";
$insert = $db->query($sql);
if ($insert) {
echo"";
}
//close connection
$db->close();
?>
How do I do that after I successfully added the values on my database?
If you're not using AJAX to call addAgent.php and your PHP and HTML are in one file, then one way would be to set a variable in your PHP like so:
if ($insert) {
$alert_success = '<div class="alert alert-success" role="alert">...</div>';
}
Then anywhere in your HTML you can add a line that echos that variable.
<?php
echo $alert_success;
?>
You could use a submit handler for your form:
// Add an ID to your form
$( "#formID" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
term = $form.find( "input[name='s']" ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, { s: term } );
// Put the results in a div
posting.done(function( data ) {
$(".modal-body, #orModalBodyID"). append('<div class="alert alert-success" role="alert">Post Success</div>')
});
});
You can find more information on jQuery's post() method # their API documentation website

I want to pop a modal when fname already exist in DB

Form:
<form class="form-horizontal" data-toggle="validator" method="post" role="form" id="enquiryForm">
<div class="form-group">
<label class="col-lg-2 control-label">Full Name :</label>
<div class="col-lg-8">
<input type="text" name="fname" class="form-control" id="inputFirstName" data-error="Please fill out this field." placeholder="Full Name" required>
<div class="help-block with-errors"></div>
</div>
<button type="button" class="btn btn-info" id="existName">Next</button>
</div>
</form>
AJAX:
$('#existName').click(function(){
var fname = $('#inputFirstName').val();
var datas = "fname="+fname;
console.log(datas);
$.ajax({
url : "exist.php",
data : datas,
method : "POST"
}).done(function(exist){
console.log(exist);
$('#existNameModal').html(exist);
})
})
PHP:
<?php
session_start();
$companydata = $_SESSION['company'];
$idCompany = $companydata['id'];
$fnameCompany = $companydata['fname'];
$lnameCompany = $companydata['lname'];
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Latest compiled and minified CSS -->
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<?php
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "gym";
$conn = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname) or die ("could not connect");
if($_POST){
$existName = $_POST['fname'];
$sql = "SELECT count(fname) from enquiry where fname = '$existName' AND cmpId = '$idCompany'";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
print_r($row);
/*exit;*/
if(($row)>0) {
$modal = '
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>';
echo $modal;
}
}
?>
</body>
</html>
Modal HTML
<!-- Name exist Modal -->
<div id="existNameModal" class="modal fade" role="dialog">
</div>
I am trying to get this Modal display when count(fname) in DB is more than 0. I tried everything but nothing worked.
From with Modal (form and modal both will be on same page)
<form class="form-horizontal" data-toggle="validator" method="post" role="form" id="enquiryForm">
<div class="form-group">
<label class="col-lg-2 control-label">Full Name :</label>
<div class="col-lg-8">
<input type="text" name="fname" class="form-control" id="inputFirstName" data-error="Please fill out this field." placeholder="Full Name" required>
<div class="help-block with-errors"></div>
</div>
<button type="button" class="btn btn-info" id="existName">Next</button>
</div>
</form>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div id="existNameModal"></div> //this is where message will show
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
In Ajax, you are using click function, better do it with change function on input and check the record if exist like
$('#inputFirstName').change(function(){
var fname = $(this).val();
//rest of code
});
The Ajax with click function
$('#existName').click(function(){
var fname = $('#inputFirstName').val();
var datas = "fname="+fname;
console.log(datas);
$.ajax({
url : "exist.php",
data : datas,
method : "POST"
})
});
Now to show modal and message if record exist
.done(function(exist){
console.log(exist);
if(exist.status=='error') {
$('#myModal').modal('show');
$('#existNameModal').html(exist.message);
}
});
The php exist.php
<?php
header('Content-Type: application/json');
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "gym";
$conn = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname) or die ("could not connect");
if($_POST['fname']){
$existName = $_POST['fname']; //escape the string
$sql = "SELECT count(fname) from enquiry where fname = '$existName' AND cmpId = '$idCompany'";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
//print_r($row);
if(($row)>0) {
$response['status'] = "error";
$response['message'] = "<div class='alert alert-danger'>Record Already Exist</div>";
}
echo json_encode($response);
}
?>

Categories

Resources