Redirect page after echo [duplicate] - php

This question already has answers here:
How do I redirect to another webpage?
(58 answers)
How do I make a redirect in PHP?
(34 answers)
Reference - What does this error mean in PHP?
(38 answers)
Page redirect after certain time PHP
(9 answers)
Closed 2 years ago.
I have checked How do I redirect to another webpage? and though they do successfully redirect, they remove the echo 'OK' function I have implemented.
I have a form and would like to redirect back to the home page 5 seconds after the form has been submitted.
However, there needs to be an echo first that says "OK" which links to a jQuery script and shows a green box that says "Your message has been sent (<div class="sent-message">). Thank you!". I would like to display that for 5 seconds, before redirecting back to the home page.
I know you cannot use header("Location: http://www.yourwebsite.com/index.html"); after echo but is there another way to do this?
This is what the form looks like when it is successfully submitted. The green box is what echo 'OK'; does. https://ibb.co/BjZ9v47
contact.php
<?php
// script to send myself an email with the data entered into the form by a user
if($mail->Send()) {
echo 'OK';
// redirect to index.html after 5 seconds
}
?>
form.html
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="captcha">
<div class="g-recaptcha" data-sitekey="my_site_key" data-callback="removeFakeCaptcha"></div>
<input type="checkbox" class="captcha-fake-field" tabindex="-1" required>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit" title="Send Message">Send Message</button></div>
</form>
jQuery script:
!(function($) {
"use strict";
$('form.php-email-form').submit(function(e) {
e.preventDefault();
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
if ( $(this).data('recaptcha-site-key') ) {
var recaptcha_site_key = $(this).data('recaptcha-site-key');
grecaptcha.ready(function() {
grecaptcha.execute(recaptcha_site_key, {action: 'php_email_form_submit'}).then(function(token) {
php_email_form_submit(this_form,action,this_form.serialize() + '&recaptcha-response=' + token);
});
});
} else {
php_email_form_submit(this_form,action,this_form.serialize());
}
return true;
});
function php_email_form_submit(this_form, action, data) {
$.ajax({
type: "POST",
url: action,
data: data,
timeout: 40000
}).done( function(msg){
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
if(!msg) {
msg = 'Form submission failed and no error message returned from: ' + action + '<br>';
}
this_form.find('.error-message').slideDown().html(msg);
}
}).fail( function(data){
console.log(data);
var error_msg = "Form submission failed!<br>";
if(data.statusText || data.status) {
error_msg += 'Status:';
if(data.statusText) {
error_msg += ' ' + data.statusText;
}
if(data.status) {
error_msg += ' ' + data.status;
}
error_msg += '<br>';
}
if(data.responseText) {
error_msg += data.responseText;
}
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(error_msg);
});
}
})(jQuery);

You can echo a <meta> refresh with a set URL, although this isn't the best approach.
if (!$mail->Send()) {
echo "Mail sending failed";
}
else {
echo "Mail sent!";
echo "<meta http-equiv='refresh' content='5;URL=/index.html'>";
}
More information about the meta tag here.

In your $.ajax done callback, inside if you can use setTimeout:
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
//redirect to specific url after 5secs
window.setTimeout(function () {
window.location.href = 'https://www.example.com'; //your home url here
}, 5000);
}

Related

how to validate the minlength and maxlength of textarea?

I want to validate the minlength and maxlength of textarea before submitting, can anyone tell me details?
<form id="contact-je" action="<?php echo JURI::current(); ?>" method="post">
<div class="input">
<label id="je_hide_message" for="message"><?php echo JText::_("$message"); ?></label>
<textarea name="je_message" id="message" class="requiredField" rows="4"
placeholder="<?php echo $message; ?>"><?php if (isset($_POST['je_message'])) {
if (function_exists('stripslashes')) {
echo stripslashes($_POST['je_message']);
} else {
echo $_POST['je_message'];
}
} ?></textarea>
<?php if (!isset($_SESSION)) {
if ($messageError != '') { ?><span
class="error"><?php echo $messageError; ?></span><?php }
} ?>
</div>
<div class="input">
<button name="submit" type="submit"
class="je_button"><?php echo JText::_("$submit") ?></button>
<input type="hidden" name="submitted" id="submitted" value="true"/>
</div>
</form>
<?php } ?>
</div>
If you are allowed to use the browser feature, you can just set minlength and maxlength attributes of <textarea>.
<form>
<textarea minlength="5" maxlength="10"></textarea>
<input type="submit">
</form>
I add following codes, but if enter more than 300characters, the form will still be submitted. I don't want to submit if the characters is over 300
// Validate error
$('form#contact-je').submit(function () {
$('form#contact-je .error').remove();
var hasError = false;
$('.requiredField').each(function () {
if ($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Pls enter ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You\'ve entered an invalid ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
}
}
});
//Limit message characters
$('#message').keyup(function() {
if ($(this).val().length > 300){
$(this).parent().append('<span class="error">ffffff</span>');
$(this).addClass('invalid');
hasError = true;
}
});
if (!hasError) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('form#contact-je').slideUp("fast", function () {
$(this).before('<span class="success"><strong>Thank you!</strong> We have received your email.<br />We will get back to you in 12 hours.<br />-- Pneuflex China</span>');
});
});
}
return false;
});

Echo div class after form is submitted

I have a contact form on my website. When a user presses submit with their details filled it, it sends me an email. However, when they click submit, a green box should appear below <div class="sent-message"> yet, when I click submit, it shows a red box and says, "mail sent". Here are the PHP lines in contact.php that are causing this...
Simply, the box should be changed to green and have the text from sent-message instead of this.
if($mail->Send()) {
echo "mail sent";
}
else {
echo "mail sent failed";
}
<div class="form">
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit" title="Send Message">Send Message</button></div>
</form>
</div>
Here is the jQuery:
!(function($) {
"use strict";
$('form.php-email-form').submit(function(e) {
e.preventDefault();
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
if ( $(this).data('recaptcha-site-key') ) {
var recaptcha_site_key = $(this).data('recaptcha-site-key');
grecaptcha.ready(function() {
grecaptcha.execute(recaptcha_site_key, {action: 'php_email_form_submit'}).then(function(token) {
php_email_form_submit(this_form,action,this_form.serialize() + '&recaptcha-response=' + token);
});
});
} else {
php_email_form_submit(this_form,action,this_form.serialize());
}
return true;
});
function php_email_form_submit(this_form, action, data) {
$.ajax({
type: "POST",
url: action,
data: data,
timeout: 40000
}).done( function(msg){
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
if(!msg) {
msg = 'Form submission failed and no error message returned from: ' + action + '<br>';
}
this_form.find('.error-message').slideDown().html(msg);
}
}).fail( function(data){
console.log(data);
var error_msg = "Form submission failed!<br>";
if(data.statusText || data.status) {
error_msg += 'Status:';
if(data.statusText) {
error_msg += ' ' + data.statusText;
}
if(data.status) {
error_msg += ' ' + data.status;
}
error_msg += '<br>';
}
if(data.responseText) {
error_msg += data.responseText;
}
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(error_msg);
});
}
})(jQuery);
You could do something like this, in contact.php:
$sent = false;
if($mail->Send()) { $sent = true; }
Then in your html you show message:
<?php
if($sent) { ?>
<div class="sent-message">Your message has been sent. Thank you!</div>
<?php } ?>
UPDATE
So your form submission is controlled by jQuery. You can show message by just echo 'OK' instead of "mail sent" in your php script
if($mail->Send()) {
echo "mail sent";
$color = 'green';
}
else {
echo "mail sent failed";
$color = 'red';
}
?>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message" style='background-color:"<?php echo $color;' ?>">Your message has been sent. Thank you!</div>
</div>
Your code must return
if($mail->Send()) {
echo "OK";
}
and if you want differen message, you can change it here:
<div class="sent-message">My new message</div>

Validating forms Ajax PHP

The jQuery/JavaScript/Ajax code is not mine. I'm learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don't understand why or how to fix it.
contact form index.html
<div class="form">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<div id="errormessage"></div>
<form action="contactform/contactform.php" method="POST" role="form" class="contactForm">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
contactform.js
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function() {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var action = $(this).attr('action');
if( ! action ) {
action = 'contactform/contactform.php';
}
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
//alert(msg);
if (msg == 'OK') {
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
} else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
return false;
});
});
contactform.php
<?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');
//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;
//Add new message
if (isset($_POST['name'])){
//Get values
$contactFormName = $_POST['name'];
$contactFormEmail = $_POST['email'];
$contactFormSubject = $_POST['subject'];
$contactFormMessage = $_POST['message'];
// 1. check name form field
if($checkStep == 1){
if($contactFormName === $_POST['name']){
$contactFormName = filterName($contactFormName);
$checkStep++;
}else{
echo "No its not working";
}
}
// 2. check email field
if($checkStep == 2){
if($contactFormEmail === $_POST['email']){
$contactFormEmail = filterEmail($contactFormEmail);
$checkStep++;
}else{
echo "Uh Oh! Something went wrong with your email please try again!";
}
}
// 3. check subject
if($checkStep == 3){
if($contactFormSubject === $_POST['subject']){
$contactFormSubject = filterSubject($contactFormSubject);
$checkStep++;
}else{
echo "Uh Oh! Whats up with your subject";
}
}
// 4. check message
if($checkStep == 4){
if($contactFormMessage === $_POST['message']){
$contactFormMessage = filterMessage($contactFormMessage);
$checkStep++;
}else{
echo "Uh ho! Please write us a message";
}
}
// 5. insert message
if($checkStep == 5){
$sqlAddMessage = "
INSERT INTO contact_form(
name,
email,
subject,
message
) VALUES(
'$contactFormName',
'$contactFormEmail',
'$contactFormSubject',
'$contactFormMessage'
)
";
$queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);
if($queryAddMessage){
//code goes here
}
}else{
echo "Uh Oh! NO No No. Check step 5";
}
}
?>
The issue is that you're not setting $msg = "OK" anywhere in your function so the AJAX response is always going to the else statement.
contactform.php (in // 5. section)
if($queryAddMessage){
echo "OK";
}
You should echo msg checked by js in php as OK
if($queryAddMessage){
//code goes here
echo 'OK';
}
Just use a jQuery form validation plugin to validate form and its easier than using AJAX for the same.

Php Ajax and html5 form integration of contact form

I am having experience in PHP and HTML but not much familiar with Ajax. Can anyone help me out here to integrate my contact form, please check my code below what modification can be required in PHP and ajax code. If I remove ajax its working fine after including ajax form is not getting posted
HTML Code
<div class="col-lg-6">
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="col-md-6 form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
Php code
<?php
require_once 'include/DB_Functions.php';
require 'send-grid/vendor/autoload.php';
$db = new DB_Functions();
if (isset($_POST['contact'])){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if ($db->storeform($name,$email,$phone,$subject,$message)) {
$memail = new \SendGrid\Mail\Mail();
$memail->setFrom("info#probig.in", "Probig Consulting");
$memail->setSubject("We have received your message");
$memail->addTo($email);
$raw_html = file_get_contents('email.html');
$getvar= array('%name%');
$repvar= array($name);
$femail=str_replace($getvar, $repvar, $raw_html);
$memail->addContent( "text/html", $femail);
$sendgrid = new \SendGrid('key');
try {
$response = $sendgrid->send($memail);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
$email2 = new \SendGrid\Mail\Mail();
$email2->setFrom("noreply#probig.in", "Probig Consulting");
$email2->setSubject($subject);
$email2->addTo("info#probig.in");
$email2->addContent("text/plain", "Name:".$name."<br><br>Mobile:".$phone."<br><br>Message:".$message);
$sendgrid = new \SendGrid('Key');
try {
$response = $sendgrid->send($email2);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
header("Location:msgsent.html");
}else{
echo "cant send message";
}
}
?>
AJax code:
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.php-email-form').submit(function() {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg) {
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(msg);
}
}
});
return false;
});
});

stop form from submitting (tried e.preventDefault() after $.post but it stops form from submitting

I have this in javascript
$('#submit').on('click', function(e) {
$('#message_line').text("");
if(validate_fields_on_submit()) {
e.preventDefault();
return;
}
// e.preventDefault();
var params = $('form').serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
// e.preventDefault();
//return false;
});
function submitHandler(response) {
$('#message_line').text("");
response = $.trim(response);
if(response == "" && response.indexOf("<") <= -1)
$('#registration').submit();
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
return false;
} else {
var name = $('[name="regusername"]').val();
var arr = response.split(',');
arr.pop();
arr.toString();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
return false;
}
$('#busy_wait').css('display','none');
}
HTML CODE
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("db/helper_functions.php");
if(validate_fields()) {
if(!check_duplicate($_POST["regusername"])) {
$count = insert_record($_POST["fname"],$_POST["lname"],$_POST["email"],$_POST["regusername"],$_POST["regpassword"]);
if($count > 0) {
include("includes/confirmation.php");
exit();
}
else {
$error = "Sorry registration failed, please try again.";
}
}
else {
$error = "Username already exists, please try different username.";
}
}
}
$page_title = "Registration";
if(isset($_SESSION["username"]))
include('includes/header_authorized.html');
else
include('includes/header.html');
?>
<div class="container">
<div class="regform">
<form name="registration" id="registration" method="post" action="registration.php">
<p><span class="req">* required field.</span></p>
<ul>
<li><label for="fname">First Name:</label>
<input type="text" class="textboxborder" id="fname" name="fname" size="20" maxlength="25" autofocus="autofocus" value="<?php if(isset($_POST['fname'])) echo $_POST['fname'];?>"/>
<span class="error" id="errfname">*<?php if(isset($errfname)) echo $errfname;?></span>
</li>
<li><label for="lname">Last Name:</label>
<input type="text" class="textboxborder" id="lname" name="lname" size="20" maxlength="25" value="<?php if(isset($_POST['lname'])) echo $_POST['lname'];?>"/>
<span class="error" id ="errlname">*<?php if(isset($errlname)) echo $errlname;?></span>
</li>
<li><label for="email">Email:</label>
<input type="text" class="textboxborder" name="email" id="email" size="40" maxlength="50" placeholder="abc#xyz.com" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/>
<span class="error" id="erremail">*<?php if(isset($erremail)) echo $erremail;?></span>
</li>
<li><label for="regusername">Username:</label>
<input type="text" name="regusername" id="regusername" size="20" maxlength="30" value="<?php if(isset($_POST['regusername'])) echo $_POST['regusername'];?>"/>
<span class="error" id="errregusername">*<?php if(isset($errregusername)) echo $errregusername;?></span>
</li>
<li><label for="regpassword">Password:</label>
<input type="password" name="regpassword" id="regpassword" size="20" maxlength="15" value="<?php if(isset($_POST['regpassword'])) echo $_POST['regpassword'];?>"/>
<span class="error" id="errregpassword">*<?php if(isset($errregpassword)) echo $errregpassword;?></span>
</li>
<li><label for="regconpassword">Confirm Password:</label>
<input type="password" name="regconpassword" id="regconpassword" size="20" maxlength="15"/>
<span class="error" id="errregconpassword">*<?php if(isset($errregconpassword)) echo $errregconpassword;?></span>
</li>
</ul>
<div id="message_line"> <?php if(isset($error)) echo $error;?></div>
<div class="buttons">
<input type="reset" value="Reset" id="reset"/>
<input type="submit" value="Submit" />
</div>
</form>
<img src="images/loading.gif" id="busy_wait" alt="busy wait icon" />
</div>
</div>
</body>
</html>
If in submit handler control goes in else if or else block form submission does not stop,I tried return false; and I tried using e.preventDefault(); at different places before ajax call and after but that stops form submission even after validation success and successful return from check_duplicate.php
Any help would be appreciated.
Assuming you have a submit button with id=submit, I would
rename the button since calling anything submit is poor practice since you need to actually submit the form programatically.
move the handler to the form submit event - I personally NEVER attach a handler to a submit button
I assume you do NOT want to submit if the validation returns false
Like this
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
var params = $(this).serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
});
the post can be written
$.post('check_duplicate.php', params, submitHandler);
UPDATE Here is the complete script - NOTE IMPERATIVE to rename anything name=submit or id=submit to something else
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
$.post('check_duplicate.php', $(this).serialize(), function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
$('#registration').submit(); // actually submit the form
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
Update3:
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
var $thisForm=$(this); // save for later
var params = $thisForm.serialize();
$.post('check_duplicate.php', params, function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
// actually submit the form
$.post($thisForm.prop("action"), params, function(response) {
if (response.indexOf("success") !=-1) {
$('#message_line').text(response);
}
else {
$('#message_line').text("something went wrong");
}
$('#busy_wait').hide();
});
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
To prevent form submission the best method will be to return false on the onclick client event
Eg
$('#submit').click(function(){
return false;
})

Categories