jQuery AJAX error handling issue - php

i am making a form that on success will display a bootstrap modal with success or with fail text. The problem that i am facing is that my success part is working the modal gets displayed with the success message but the fail part brings up the modal but empty, its missing the error text. I don't seem to find the problem maybe its because i have been looking at it for a long time now. Any help would be much appreciated.
Code is the following:
HTML:
<form id="ajax-contact" method="post" action="mail.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control msg" id="name" name="name" placeholder="Your name..." required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control msg" id="email" name="email" placeholder="Your email address..." required>
</div>
<div class="form-group">
<label for="select">Category:</label>
<select class="form-control msg" id="select" name="select" required>
<option value="">Select a category</option>
<option value="Website building">Website building</option>
<option value="Template creation">Template creation</option>
<option value="Logo Design">Logo Design</option>
<option value="Mobile App">Mobile App</option>
<option value="SEO Services">SEO Services</option>
</select>
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="text" class="form-control msg" id="subject" name="subject" placeholder="Message subject..." required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" rows="5" id="message" name="message" placeholder="Type your message here..." required></textarea>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<h1 id="form-messages" class="text-center">
</h1>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default center-block modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-default msg-button" data-toggle="modal" data-target="#myModal">Submit</button>
</form>
PHP:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$subject = strip_tags(trim($_POST["subject"]));
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
$select = trim($_POST["select"]);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if (empty($name) OR empty($message) OR empty($subject) OR empty($select) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "info#email.com";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Category: $select\n";
$email_content .= "Subject: $subject\n\n";
$email_content .= "Message: $message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Jquery:
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// TODO: The rest of the code will go here...
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
success: function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
console.log(response);
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#select').val('');
$('#subject').val('');
$('#message').val('');
},
error: function(textStatus) {
alert("asd");
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
console.log(textStatus);
// Set the message text.
if (textStatus !== '') {
$(formMessages).text(textStatus);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
}
});
});
});

Change
$(form).submit(function(event) {
to
$(form).find('[type="submit"]').click(function(event) {
And you would get
// Oops! There was a problem with your submission. Please complete the form and try again.
Problem was you are using the form tag and HTML5 wont allow to submit form untill required fields are filled, so your was form not getting submitted in first place.

Related

Sweetalert (Ajx - PHP Form) only show success (alert) even when input fields are empty

I've try so may different ways to make this work, but no luck. Every time I submit the form the success swal alert is the one firing even on empty fields.
This is my HTML
<!-- Content -->
<div class="content">
<form role="form" id="form" action="assets/php/mail.php" method="post">
<div class="row 50%">
<div class="6u 12u(mobile)">
<label for="name"></label>
<input id="name" type="text" name="name" placeholder="Name"/>
<span></span>
</div>
<div class="6u 12u(mobile)">
<label for="email"></label>
<input id="email" type="email" name="email" placeholder="Email"/>
</div>
</div>
<div class="row 50%">
<div class="12u">
<textarea id="message" name="message" placeholder="Message" rows="7"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="buttons">
<li><input id="submit-button" type="submit" class="special" value="Send" /></li>
</ul>
</div>
</div>
</form>
</div>
This is JS The empty swal I.m using it to clear the form once is submitted is the only way that I got it to work.
$(document).ready(function(){
$('#form').on('submit',function(e) { //Don't foget to change the id form
$.ajax({
url:'assets/php/mail.php', //===PHP file name====
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
//Success Message == 'Title', 'Message body', Last one leave as it is
swal({
type: 'success',
title: 'Submmited',
text: 'Your message has been send!'
}).then((result) => {
if (result.value) {
$("#name").val("");
$("#email").val("");
$("#message").val("");
swal()
}
});
},
error:function(data){
//Error Message == 'Title', 'Message body', Last one leave as it is
swal({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: '<a href>Why do I have this issue?</a>'
})
}
});
e.preventDefault(); //This is to Avoid Page Refresh and Fire the Event "Click"
});
});
This is my PHP I use so many different php codes for this but this is the one that actual work best for me.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check the data.
if (empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../../contact.html");
exit;
}
$recipient = "php_test#knobcode.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
mail($recipient, $subject, $email_content, $email_headers);
header("Location: ../../contact.html");
Try checking the inputs in the submit handler:
$('#form').on('submit',function(e) {
e.preventDefault();
if( $(this).find("[name='name']").val()!="" && // If the 3 aren't empty, it proceeds.
$(this).find("[name='email']").val()!="" &&
$(this).find("[name='message']").text()!=""
){
// The rest of your code here...
}else{
alert("Please fill the form before submitting!"); // Or use a swal...
}
});
About Ajax: The success callback fires when the Ajax resquest is successful regardless of the data sent. The error callback fires when the Ajax request cannot be completed... Like because of a wrong URL or something.

Ajax not capturing php contact form script

I have a contact form on my website that is not posting the success or error message as it should.
The weird thing is I have used this exact same form, php, and ajax script on several other sites and it works great. In fact, it used to work great on the site in question.
The website is https://www.pouncingfoxdesign.com. The contact form is at the bottom. Feel free to fill it out for testing purposes.
Here's the form and script:
<div class="col-md-8 col-sm-9 wow form1 fadeInLeft">
<div class="contact-form clearfix contactForm">
<form id="form" action="php/email.php" class="contactForm"
method="post">
<div class="messages"></div>
<div class="input-field">
<input type="text" class="form-control" name="name"
placeholder="Your Name" required="">
</div>
<div class="input-field">
<input type="email" class="form-control"
name="email" placeholder="Your Email" required="">
</div>
<div class="input-field message">
<textarea name="message" class="form-control"
placeholder="Your Message" required=""></textarea>
</div>
<input type="submit" name="submit" class="btn btn-blue
pull-right" value="SEND MESSAGE" id="msg-submit">
<div class="g-recaptcha fadeInLeft" data-
sitekey=""></div>
</form>
</div> <!-- end .contact-form -->
</div> <!-- .col-md-8 -->
<script> $('#form').on('submit', function(e) {
event.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize(); //Serialized the form data for
process.php
// $('#loader', '#form').html('<img src="img/forms/loading.gif" />
Please Wait...');
$.ajax({
type: 'POST',
url: 'php/email.php', // Your form script
data: post_data,
success: function(msg) {
var old_html = form.html()
$(form)
.html(msg).fadeIn();
setTimeout(function(){
$(form)
.html(old_html).fadeIn();
}, 4000);
},
error: function(xhr, ajaxOptions, err){
var old_html = form.html()
$(form).fadeOut(500)
.html("<h3>There was an error. Please try again.
</h3>").fadeIn();
setTimeout(function(){
$(form).fadeOut(500)
.html(old_html).fadeIn();
}, 3000);
}
});
});
</script>
And here's the PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h1>Submission successful</h1>
<h3>Thank you for contacting us!</h3>
</div>
</div>";
$to = "email#email.com";
$subject = "$name\n filled Pouncing Fox Desing Form";
$txt = "From: $name\n E-Mail: $email\n Comments:\n $message";
$headers = "From: Pouncing Fox Design" . "\r\n" ;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents
("https://www.google.com/recaptcha/api/siteverify?
secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if (mail($to, $subject, $txt, $headers)) {
echo "$success"
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
What I want it to do is replace the form with the success message for a few seconds and then go back to the form. What it does instead is just go to the email.php file with the success message being all that's on the screen.
If you want to check out https://www.mooreengaging.com, the same script and php file is used for that site. It works great and you can see my intended results. Again, feel free to fill out the form for testing purposes.
I have tried to use other ajax scripts and have tried to rework it several different times, but no matter what when clicking submit it just loads the php file. It's like it is bypassing the ajax script altogether.
Thanks!
EDIT:
I have received the emails from you guys testing and they look right. So it is working, just not posting the success message as I'd like.
Ok, I figured it out. I added <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> to the top of the page under the header.
I thought it was best to put jquery at the bottom?
Did it fail because I was trying to run that script before it loaded jquery?
Change
$('#form').on('submit', function(e)
To
$('#form').on('submit', function(event)
Because you use
event.preventDefault();

Form sending email but in the email $_POST values are blank

I have read many forums where this exact question posted but there is no satisfactory answer. Some posts seem to have found out how to make it work but the answer is not shared or only partly answered.
the answer that i see the most is (but don't know how to use it):
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post("sendemail.php", $(".contact-form").serialize(),function(result){
if(result.type == 'success'){
$this.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
});
return false;
});
the problem with this is that $_POST is not being sent. The mail function is working but the mail contents are blank
my mail message:
Name:
Email:
Subject:
Message:
exactly this is in my mail when I fill the form with data and nothing is being sent
main.html
<h4>Contact Form</h4>
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-5">
<div class="form-group">
<input type="text" class="form-control" name="subject" required="required" placeholder="Subject">
</div>
<div class="form-group">
<input type="text" class="form-control" name="name" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" required placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Send Message</button>
</div>
</div>
<div class="col-sm-7">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Message"></textarea>
</div>
</div>
</form>
sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'myEmail#gmail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
Is your form possibly getting submitted twice? (once completed and then blank) The html form is already fully wired to POST without the use of the submit handler, which is redundant.
If I'm going to submit a form via AJAX, I typically set only the id of the form (i.e. no action and no method attributes) and I use a regular button (not submit) as the submit button. This makes it clear that jQuery will be handling the POSTing.
<form id="main-contact-form" class="contact-form" role="form">
...fields
<button id="btn_submit" class="btn btn-primary">Submit</button>
</form>
Then in jQuery
'use strict';
var form = $('.contact-form'),
btn_submit = $('#btn_submit');
btn_submit.on('click', function(e) {
e.preventDefault(); //prevent default button behavior
$.post('sendemail.php', form.serialize(),function(result){
if(result.type == 'success'){
form.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
});
Change your "jquery" code as shown below:
$('.contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
$this = $(this);
$.post(
"sendemail.php",
$(".contact-form").serialize(),
function(result){
if(result.type == 'success'){
$this.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
},
'json' // expecting a JSON response from server
);
});
I think you have multiple forms with the css class .contact-form in the same page. If you want to submit this form, then you can use form id selector.
<script type="text/javascript">
$(function() {
$('#main-contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
var $this = $(this);
$.post("sendemail.php", $this.serialize(), function(result) {
if (result.type == 'success') {
$this.prev().text(result.message)
.fadeIn().delay(3000).fadeOut();
}
}
}, 'json');
});
</script>
Or you can write the code using the css selector as follows:
<script type="text/javascript">
$(function() {
$('.contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
var $this = $(this);
$.post("sendemail.php", $this.serialize(), function(result) {
if (result.type == 'success') {
$this.prev().text(result.message)
.fadeIn().delay(3000).fadeOut();
}
}
}, 'json');
});
</script>

Send php mail using html webform

I have set up a page that is still in construction and i'm building a webform for users to contact me.
When i fill the webform and hit the "send" button, message gets send succesfully and i receieve it on my mail...but when i hit the "send" button, i get re-directed off page, saying it was sent successfully.
How can i prompt user that the message was sent successfully, without getting redirected of page, and get the message in same window?
This is my HTML code
<form action="assets/php/contactUs.php" id="contact" class="form" role="form" method="post">
<div class="row">
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="name" name="name" placeholder="Name" type="text" required />
</div>
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required />
</div>
</div>
<textarea class="form-control" id="message" name="message" placeholder="Message" rows="5"></textarea>
<div class="row">
<div class="col-xs-12 col-md-12">
<button class="btn btn btn-lg">Send Message</button>
</div>
</div>
</form>
And this is my contactUs.php code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$message = <<<EMAIL
$message
From: $name
My email is: $email
EMAIL;
$to = "mymail#mymail.com";
$subject = "New Customer Enquiry";
mail($to, $subject, $message, "From: " . $email);
echo "Thank you, your message has been successfully sent!";
?>
AJAX
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('.btn-lg').click(function(){
$.post( "assets/php/contactUs.php", $( "#contact" ).serialize(), function(msg){
alert(msg);
} );
});
});
</script>
This is a result of successfully sent message.
Please guys help me out! Thanks!
REDIRECT OPTION
$firstpageurl = 'http://example.com';
echo "Your message has been successfully sent!";
$header('Location: '.$firstpageurl);
Use Ajax as below.Change the submit type button to a normal button by removing the type attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('.btn-lg').click(function(event){
$.post( "config.php", $( "#contact" ).serialize(), function(msg){
alert(msg);
} );
event.preventDefault();
});
});
</script>
The action part of your form tag is "assets/php/contactUs.php"
<form action="assets/php/contactUs.php" id="contact" class="form" role="form" method="post">
That means that posting this form will bring you to that page. You can either code that page to send the email and redirect them back like this...
header('Location: '.$firstpageurl);
or put the php code into this first page and remove the entire action property. If you put the php on this page, you need to wrap your code in an if so that people can load the page before posting the form.
if (isset($_POST['email'])){
echo "Sent email";
[email send code here]
}
as for putting the message saying it's sent...that will only work with the second method. To do it without a full page load at all do it with ajax.
You want to use JQuery for that.
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#contact").submit(function(){
var form_data=$("form").serialize();
$.post( "assets/php/contactUs.php",form_data, function( data ) {
alert(data);
});
event.preventDefault();
});
</script>
You can do it without using Javascript. Do the following:
Set the form to post to itself (e.g. if your form was on index.php, set action="index.php"
When the page loads, check $_POST to see if the form values were sent.
If the $_POST values are empty, display the form
If the $_POST values are set, do what you need to do with those values, then output your results into the page.
Here's a really simple example demonstrating what I mean.
<?php
$submitted = false;
if (isset($_POST["myinput"]) && $_POST["myinput"] != '') {
$submitted = true;
}
?>
<?php
if ($submitted == false) {
?>
<form action="index.php" method="post">
<input name="myinput"><input type="submit">
</form>
<?php } else { ?>
<h1>Form Submitted</h1>
<?php } ?>

How do I prevent PHP file from popping up after submitting contact form?

Right now, whenever I click the submit button on the contact form on my website, it brings me to the page www.mysite.com/php/function/email.php, rather than running the email.php in the background like I want it to.
The website is supposed to allow you to submit the contact form, then the button will fade away and fade in a "Your message has been sent!", then fade back the button.
HTML:
<form name="contact form" id='contact_form' method="post" action="php/function/email.php">
<div class="row half">
<div class="6u">
<input name="name" placeholder="Name" type="text" class="text" />
</div>
<div class="6u">
<input name="email" placeholder="Email" type="email" class="text" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" placeholder="Message"></textarea>
</div>
</div>
<div class="row half">
<div class="12u">
<input id="submit" name="submit" type="submit" value="Send Message" class="button button-icon icon icon-envelope" />
</div>
</div>
<p id="success" style="display:none">Your message has been sent! I'll get back to you soon!</p>
<p id="error" style="display:none">Please fill in all the fields and try again!</p>
JS:
$(document).ready(function(){
$('#send_message').click(function(e){
//Stop form submission & check the validation
e.preventDefault();
// Variable declaration
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
// Disable submit button just after the form processed 1st time successfully.
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("email.php", $("#contact_form").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
//If the email is sent successfully, remove the submit button
$('#submit').remove();
//Display the success message
$('#success').fadeIn(500);
}else{
//Display the error message
$('#error').fadeIn(500);
// Enable the submit button again
$('#submit').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
};
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: Example';
$to = 'example#gmail.com';
$subject = 'Example Contact Form';
$body = "
From: $name
Email: $email
---------------
Message: \n
$message";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo 'sent';
} else {
echo 'failed';
}
}
?>
The .click() event of a <input type="submit"> isn't actually what causes the redirection. It instead becomes a .submit() event at the <form>.
You can either e.stopPropagation() so it doesn't reach the <form>.
//Stop form submission & check the validation
e.stopPropagation();
Or preventDefault() of the <form>'s .submit().
$('#contact_form').submit(function (e) {
e.preventDefault();
});
Note: You should also consider moving your code into a .submit() handler as most browsers support other ways of submitting a <form> than actually clicking the <input type="submit">.
The problem is that you're looking for click events on #send_message but your submit button has an id of submit. So that click event never happens.

Categories