I have a form which works fine but after submitting it reloads the page. I want it to display the message under the form instead of reloading the page.
Here is my html code:
<form class=" form-horizontal" action="php/contact.php" method="post" id="contact_form" name="contact-form">
<fieldset>
<div class="form-group">
<input name="firstname" placeholder="First Name" class="form-control" type="text">
<input name="lastname" placeholder="Last Name" id="lastname" class="form-control" type="text">
<input name="email" placeholder="E-Mail Address" class="form-control" type="text">
<input type="text" name="mail"> <!-- anti spam - needs to stay non-filled - hidden by css -->
<input name="phone" placeholder="(+44) 020 1234 5678" class="form-control" type="text">
<input name="company" placeholder="Company name" class="form-control" type="text">
<input name="website" placeholder="Website or domain name" class="form-control" type="text">
<textarea class="form-control" name="message" placeholder="Your message"></textarea>
<!-- Success message -->
<div class="alert alert-success" role="alert" id="success_message">
Thanks for contacting us, we will get back to you shortly.</div>
<button type="submit" class="btn btn-block btn-primary">Send <span class="fa fa-fw fa-lg fa-send"></span> </button>
</div>
</fieldset>
</form>
I also use jquery validation scripts and this is a quick summary to this script ( I believe the most of changes need to be done here):
$(function() {
$("form[name='contact-form']").validate({
rules: {
firstname: "required",
message: "required",
email: {
required: true,
email: true
},
},
messages: {
firstname: " Please enter your firstname",
email: " Please enter a valid email address",
message: " Please type your message"
},
submitHandler: function(form) {
form.submit();
}
});
});
And this is a php code, which reloads the page after submitting:
<?php
$adresdo = "info#tucado.com";
$temat = "Message from tucado.com";
$zawartosc = "First Name: ".$_POST['firstname']."\n"
."Last Name: ".$_POST['lastname']."\n"
."Company: ".$_POST['company']."\n"
."Email: ".$_POST['email']."\n"
."Telephone: ".$_POST['phone']."\n"
."Website: ".$_POST['website']."\n"
."Message: ".$_POST['message']."\n";
if(!$_POST['firstname'] || !$_POST['email'] || !$_POST['message']){
header("Location: ../contact.html");
exit;
}
$email = $_POST['email'];
if(mail($adresdo, $temat, $zawartosc, 'From: Contact <'.$email.'>')){
header("Location: ../msg-sent.html");
}
?>
Could you please help me in modifying this code to display a message (id="success_message") when the message is sent? Thank you for your help.
Try ajax submission. put ajax code inside submit handler, use serialise or formdata to fetch the whole form .See example.
submitHandler: function(form) {
$.ajax({
url: "name_of_file.php",
type: "POST",
data: new FormData($(form)),
cache: false,
success: function(data) {
$("#success_message").html(data);
}
});
return false;
},
echo desired output in the php file so as to retreive it in data.
Related
I am having a registration form once user submit the form not clearing the data and it is not displaying the success message as well.here the code which i have written for registration form.
Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('error_messages', 'english');
$this->load->model(VERSION . DOCTOR_MODEL_FOLDER . 'Doctor_model', 'doctors');
$this->load->helper('gmaps');
$this->load->library('locations');
}
public function createAccount() {
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email_id');
$password = $this->input->post('password');
$phone_number = $this->input->post('phone_number_with_ext');
$reg_no = $this->input->post('reg_no');
$regDetails = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email_id' => $email,
'password' => $password,
'reg_no' => $reg_no,
'mobile_no' => $phone_number,
);
$regMessage = $this->doctors->register($regDetails);
//if registration done successfully
if (is_string($regMessage)) {
$data['success'] = true;
$data['response'] = $phone_number;
} else {
//if there is error
$data['success'] = false;
$data['error_msg'] = $regMessage;
}
die(json_encode($data));
}
View:
<div class="form">
<div class="alert" style="display: none;"></div>
<form class="form-validate form-horizontal " id="register_form" method="post" action="" enctype="multipart/form-data">
<div class="form-group ">
<div>
<input class=" form-control" placeholder="First Name" id="first_name" name="first_name" type="text" />
</div>
</div>
<div class="form-group ">
<div>
<input class=" form-control" placeholder="Last Name" id="last_name" name="last_name" type="text" />
</div>
</div>
<div class="form-group ">
<div>
<input class=" form-control" placeholder="Email Address" id="email_id" name="email_id" type="text" />
</div>
</div>
<div class="form-group ">
<div>
<input class="form-control country-code" placeholder="Phone Number" id="phone_number" name="phone_number" type="tel" />
</div>
</div>
<div class="form-group ">
<div>
<input type="text" class="form-control " placeholder="Registration number" id="reg_no" name="reg_no">
</div>
</div>
<div class="form-group ">
<div>
<input class="form-control " placeholder="Password" id="password" name="password" type="password" />
</div>
</div>
<div class="form-group ">
<div>
<input class="form-control " placeholder="Re-enter Password" id="confirm_password" name="confirm_password" type="password" />
</div>
</div>
<div class="form-group">
<div>
<button type="submit" id="btnRegister" class="btn btn-primary btn-lg btn-block">Submit</button>
</div>
</div>
</form>
</div>
JS:
// Submit registration form on button click last_name:{ required: true},
$('form#register_form').validate({
rules: {
first_name: {
required: true,
alpha: true
},
email_id: {
required: true,
email: true
},
phone_number: {
required: true,
number: true,
minlength: 8,
maxlength: 10
},
password: {
required: true,
minlength: 6
},
confirm_password: {
required: true,
minlength: 6,
equalTo: "#password"
},
},
messages: {
first_name: {
required: "Please enter First Name.",
alpha: "Special Characters not allowed."
},
email_id: {
required: "Please enter a email address.",
email: "Please enter a valid email address."
},
phone_number: {
required: "Please enter Phone Number." ,
number: "Please enter Numeric values for Phone Number."
},
password: {
required: "Please provide a password.",
minlength: "Your password must be at least 6 characters long."
},
confirm_password: {
required: "Please provide a password.",
minlength: "Your password must be at least 6 characters long.",
equalTo: "Please enter the same password as above."
},
},
submitHandler: function(form) {
var post_data = $("#register_form").serializeArray();
//var phoneExten = $("ul.country-list li.active").attr('data-dial-code');
var phoneExt = $("#phone_number").intlTelInput("getNumber");
post_data.push({name: "phone_number_with_ext", value: phoneExt});
//console.log(post_data);
$.ajax({
url: "/createAccount",
type: "POST",
data: post_data
}).done(function(res) {
//console.log(res);
var data = $.parseJSON(res);
if( data.success){
$('form#register_form div.form div.alert').removeClass('alert-danger').addClass('alert-success').text('User Created Successfully.').show().delay(2000).fadeOut('slow');
}else{
$('div.form div.alert').addClass('alert-danger').text(data.error_msg.message).show().delay(2000).fadeOut('slow');
$("div.form").scrollTop();
}
});
}
});
Added success message in javascript it is working fine for failure message but not working for success message and once data is submitting it is displaying the data still in form fields.Not getting the data cleared.
Following line work like: first it find from#register_form withing the elements it next find div.form (which isn't inside the form#register_form) then jquery try to find div.alert withing div.form which is not found in your current HTML structure.
div.form is parent node of form#register_form.
$('form#register_form div.form div.alert').removeClass('alert-danger').addClass('alert-success').text('User Created Successfully.').show().delay(2000).fadeOut('slow');
You should change it to:
$('div.alert').removeClass('alert-danger').addClass('alert-success').text('User Created Successfully.').show().delay(2000).fadeOut('slow');
As far as you're submitting form through AJAX you need to clear out all form fields using jquery. You can do it like.
$('form#register_form').trigger("reset");
After end of the code use this line to refresh the page:
redirect('Login/createAccount','refresh');
For Success message:
In Controller Code:
$this->session->set_flashdata('Add', 'Your da`ta added Successfully..');
redirect('Login/createAccount','refresh');
In View page after body:
<?php if($this->session->flashdata('Add')){ ?>
<center><div id="successMessage" class="alert bg-success alert-styled-left">
<button type="button" class="close" data-dismiss="alert"><span>×</span><span class="sr-only">Close</span></button>
<span class="text-semibold"><?php echo $this->session->flashdata('Add'); ?></span>
</div></center>
<?php } ?>
Javascript code for disable the flash data after particular time:
<script type="text/javascript">
$(document).ready(function(){
$("#successMessage").delay(5000).slideUp(300);
});
</script>
I am trying to submit a form using Ajax, the problem is the validation file I made is not called at all (I checked it by putting a bit of js alert inside the PHP validation file). I searched the internet and tried a lot of solutions but none worked. Is there something wrong I am making in my code?
Here is my HTML:
<form method="post" id="signup">
<div class="form-group">
<input type="fname" name="fname" id="fname" value="" class="form-control" placeholder="Your First name" />
</div>
<div class="form-group">
<input type="lname" name="lname" id="lname" value="" class="form-control" placeholder="Your Last name" />
</div>
<div class="form-group">
<input type="email" name="email" id="email" value="" class="form-control" placeholder="Your Email" />
</div>
<div class="form-group">
<input type="password" name="password" id="password" value="" class="form-control" placeholder="Your Password" />
</div>
<div class="form-group submit-btn">
<input id="signupsumbit" type="submit" name="submit" value="Sign Up" class="btn btn-success btn-lg"/>
</div>
</form>
And here is the ajax call:
$(function (){
$('#signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $('#signup').serialize(),
url: 'login.php',
success: function (data) {
alert("data is"+data);
}
});
});
});
Here is a bit of my PHP code:
include("connection.php");
echo "<script>alert(2)</script>";
if (isset($_GET['logout']) and $_GET['logout']==1 and isset($_COOKIE[id]))
{
setcookie("email", '', time()-60*60*24);
setcookie("password", '', time()-60*60*24);
setcookie("id", '', time()-60*60*24);
$message = "You have been logged out! Come back soon!";
}
if(mysqli_connect_error()) // if failed to connect to database
{
die("Could not connect to database"); //stop the whole script from runnning
}
if (isset($_POST['submit']) and $_POST['submit'] == 'Sign Up')
{
echo '<script>console.log(1)</script>'; //
$error = '';
$success = '';
// email validation
$email = $_POST['email'];
if (empty($_POST['email']))
{
$error .="<br />Please enter your email";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .="<br />Please enter a valid email address";
}
}
.
.
.
.
?>
And of course, the PHP file I made validation at is called login.php.
As you may notice, I put two alerts in my PHP code, I alerted 2 to make sure that the file is called, and alerted 1 to make sure that the form was posted. Odds are, when I submit the form the normal way (with no AJAX), both of alerts work, but when I submit it with AJAX, none of them is alerted.
My Console shows this:
Any help would be appreciated. Thanks.
Testing your script, i found that the submit button is not sent to your login.php script. If you e.preventDefault() and then later trigger the submit, javascript was submitting the form but not the button. To fix your issue create a hidden field with name submit and value Sign Up and remove the name attribute from your submit button (don't need that) and it should work fine.
<form method="post" id="signup">
<input type="hidden" name="submit" value="Sign Up"> <!-- note this hidden field -->
<div class="form-group">
<input type="fname" name="fname" id="fname" value="" class="form-control" placeholder="Your First name" />
</div>
<div class="form-group">
<input type="lname" name="lname" id="lname" value="" class="form-control" placeholder="Your Last name" />
</div>
<div class="form-group">
<input type="email" name="email" id="email" value="" class="form-control" placeholder="Your Email" />
</div>
<div class="form-group">
<input type="password" name="password" id="password" value="" class="form-control" placeholder="Your Password" />
</div>
<div class="form-group submit-btn">
<input id="signupsumbit" type="submit" value="Sign Up" class="btn btn-success btn-lg"/><!-- note the removed name attribute -->
</div>
</form>
My contact form doesn't seem to work. I don't know what is wrong. I tried all sorts of solutions, nothing works. My pages still refreshes. Maybe anyone can spot a mistake that I did or perhaps offer alternative code? I would really appreciate your help!
return: false; doesn't work. neither does e.prevenDefault();. Don't ask why.
HTML
<form action="" method="post" id="contact-form">
<div class="row">
<div class="medium-3 columns">
<label>
<input type="text" id="name" placeholder="Your name*" name="name" required/>
</label>
</div>
<div class="medium-3 columns">
<label>
<input type="email" id="email" name="email" placeholder="Your e-mail*" required/>
</label>
</div>
<div class="medium-3 columns">
<label>
<input type="text" id="compname" name="compname" placeholder="Company name*" required/>
</label>
</div>
<div class="medium-3 columns">
<label>
<input type="text" id="website" name="website" placeholder="Website*" required/>
</label>
</div>
</div>
<div class="row">
<div class="medium-12 columns">
<label>
<textarea type="text" row="10" name="message" id="message" placeholder="Message*" required></textarea>
</label>
</div>
</div>
<div class="row">
<button type="submit" class="button large" id="sendmessage-btn"> Send Message
</button>
</div>
<div data-alert class="alert-box success radius">Your message has been sent.×
PHP
<?php
$to = 'email#email.com';
$subject = 'Message from the contact form';
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$compname = trim($_POST['compname']);
$website = trim($_POST['website']);
$message = trim($_POST['message']);
$message = <<<EMAIL
Name: $name
Contact e-mail: $email
Company: $compname
Company website: $website
Message: $message
EMAIL;
if ($_POST) {
mail ($to, $subject, $message, $header);
} ?>
And JS
$(document).foundation();
var form = $('#contact-form');
var submitButton = $('#sendmessage-btn'); // Variable to cache button element
var alertBox = $('.alert-box'); // Variable to cache meter element
var closeButton = $('.close'); // Variable to cache close button element
$(form).submit(function () {
$.ajax({
type: 'get',
url: 'function.php',
data: $(form).serialize(),
success: function sendContactForm(){
$(submitButton).fadeOut(500); // Fades out submit button when it's clicked
setTimeout(function() { // Delays the next effect
$(alertBox).fadeIn(500); // Fades in success alert
}, 500);
};
});
});
$(closeButton).click(function() { // Initiates the reset function
$(alertBox).fadeOut(500); // Fades out success message
setTimeout(function() { // Delays the next effect
$('input, textarea').not('input[type=submit]').val(''); // Resets the input fields
$(submitButton).fadeIn(500); // Fades back in the submit button
}, 500);
return false; // This stops the success alert from being removed as we just want to hide it
});
// Your form is already a jquery object, don't wrap it again?
form.submit(function () {
$.ajax({
....
});
// Prevent default submit behavior of form.
return false;
});
I am trying to send an email with PHP and Ajax, the mailer is working but I know very little about Ajax, after reading a couple of pages of a book I have written a small piece of code and was hoping someone could point out where I am going wrong:
Here is my PHP:
<?php
$name = ($_POST['name']);
$email = ($_POST['email']);
$fsubject = ($_POST['subject']);
$message = ("Name: ". $name . "\nEmail Address: " . $email . "\n\nMessage: " . $_POST['message']);
// Set Mail
$to = "emailaddress#fakeone.com";
$headers = 'emailaddress#fakeone.com' . "\r\n";
$subject = "{$fsubject}";
$body = "{$message}";
// Send Mail
if (mail($to, $subject, $body, $header))
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
?>
My HTML:
<div id="success" style="color:red;"></div>
<form action="" id="contactform" method="post">
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Your name *</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name">
</div>
<div class="col-md-6">
<label>Your email address *</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Subject</label>
<input type="text" value="" data-msg-required="Please enter the subject." maxlength="100" class="form-control" name="subject" id="subject">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Message *</label>
<textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" id="submit" value="Send Message" class="btn btn-info btn-lg" data-loading-text="Loading...">
</div>
</form>
My AJAX:
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("sendmail.php", $("#contactform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
</script>
At the moment the same page just reloads, the desired outcome is just a subtle success or failure message appearing.
Any help would be welcome!
Thanks,
Dan
Your snippet code seems to run just fine.
It must be an error either in other JS (check browser console, F12 in Chrome for example) or in your PHP.
Try this to see if ajax post fails:
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("contact.php", $("#contactform").serialize(), function(response) {
$('#success').html(response);
}).fail(function() {
alert( "error" );
});
return false;
});
});
</script>
Also, try to make sure PHP execution is fine, so remove all javascript and replace
<form action="sendmail.php" id="contactform" method="post">
Check the result of that page, it should be "Message successfully sent!".
Also, check a simple JS snippet of your code:
http://jsfiddle.net/CPtpk/
Please note that if you have another JavaScript code in your page that could be a cause for this problem. Even if your JS error is in another place it can cause JS execution to stop and so your onClick isn't executed and that's why you get your problem...
Try something like this on the JS:
<script>
$(document).ready(function() {
$('#contactform').submit(function(e) {
e.preventDefault();
$.post("sendmail.php", $(this).serialize(), function(response) {
$('#success').html(response);
});
});
});
</script>
I have an input form builded with Bootstrap. The check of correct data is handled by javascript, and it's set that on click of button "remind me" it pop ups a notification that says that everything is correct. This last part of pop up notification is handled by php POST method, and I want the same pop up to be shown but with javascript instead of php.
The HTML is:
<form class="form-horizontal" id="registerHere" method='post' action=''>
<fieldset>
<div class="control-group">
<div class="controls">
<input type="text" class="span3" id="user_name" name="user_name" rel="popover" data-content="Enter your first and last name." data-original-title="Full Name" placeholder="First name Last name">
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="text" class="span3" id="user_email" name="user_email" rel="popover" data-content="What’s your email address?" data-original-title="Email" placeholder="me#somewhere.com">
</div>
</div>
<div class="control-group">
<div class="controls controls-row">
<input type="text" class="span1" id="inputPLZ" name="inputPLZ" placeholder="Postal" data-content="Insert your area postal code.">
<input type="text" class="span2" id="inputOrt" name="inputOrt" placeholder="Place" data-content="Where are you from?">
</div>
</div>
<div class="control-group">
<label class="control-label" for="input01"></label>
<div class="controls">
<button type="submit" class="btn btn-success" rel="tooltip" title="first tooltip">Remind me</button>
</div>
</div>
</fieldset>
</form>
and the Javascript is
<script type="text/javascript">
$(document).ready(function(){
$('#registerHere input').hover(
function(){
$(this).popover('show')
},
function(){
$(this).popover('hide')
}
);
$("#registerHere").validate({
rules:{
user_name:"required",
user_email:{
required:true,
email: true
},
},
messages:{
user_name:"Enter your first and last name",
user_email:{
required:"Enter your email address",
email:"Enter valid email address"
},
},
errorClass: "help-inline",
errorElement: "span",
highlight:function(element, errorClass, validClass) {
$(element).parents('.control-group').addClass('error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parents('.control-group').removeClass('error');
$(element).parents('.control-group').addClass('success');
}
});
});
</script>
this is PHP part that I wanna replace with Javascript:
<?php if($_POST) { ?>
<div class="alert alert-success">
Thanks, we have your info, and expect our contact really soon!
</div>
<?php } ?>
The logic you are talking about is not correct. The ear of your server-side is PHP. It is not possible to know that the form posted and the data are delivered to the server without PHP.