message alert not working - javascript

this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
Htmlcode and after html is js code
this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
--
ajax code
var form = $('#main-contact-form');
form.submit(function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function() {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function(data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
php code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$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 = 'email#email.com';//replace with your email
$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;

This is what your ajax call should look like
$('#main-contact-form').on('submit', function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url : $(this).attr('action'),
data : $(this).serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function() {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function(data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});

make sure your ajax response which is
function(data)
is really an object variable
because if not this code will not execute because of error of data.message
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
also kindly check your network status check the response of that ajax request
using the dev tools F12
UPDATED ANSWER BELOW
so your response is json but still need to be parse in your javascript.
SOLUTION: Parse your ajax response to make it json object
data = JSON.parse(data);
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();

The problem is, that you don't send your form data with the ajax-call.
Like adeneo wrote, you only have to add one line to your code.
data : $(this).serialize(),
Setting the data-type is relevant, because the destination needs to know in which format the data is sent.
Try using the Jquery-POST-function. It looks much better in the code.

Related

Contact form is sending email but not responding after submission.

I have my contact form set where after submitting it redirects back to my homepage but for some reason it just stays on the same page. I'm trying to receive confirmation after email is sent and then a redirect back to my homepage. I'm using php and javascript...........................................
<div class="col-sm-6 col-sm-offset-3">
<h3>Send me a message</h3>
<form role="form" id="contactForm" action="index2.php" method="POST">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" required>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" required>
</div>
</div>
<div class="form-group">
<label for="message" class="h4 ">Message</label>
<textarea id="message" class="form-control" rows="5"
placeholder="Enter your message" required></textarea>
</div>
<button type="submit" id="form-submit" class="btn btn-primary btn-lg
pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden">Message Submitted!</div>
</form>
index2.php
<meta http-equiv="refresh" content="0; url=http://myurl.com/" />
</header>
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$EmailTo = "arash281pro#live.com";
$Subject = "New Message Received";
// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success){
echo "success";
}else{
echo "invalid";
}
?>
js
$("#contactForm").submit(function(event){
// cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "index2.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$( "#msgSubmit" ).removeClass( "hidden" );
}
var confirmSubmit = true;
$('form').submit(function(e) {
if (confirmSubmit) {
e.stopPropagation();
if (confirm('Are you sure you want to send this form?')) {
confirmSubmit = false;
$('form').submit();
}else{
alert("The form was not submitted.");
}
}
});
You're not actually redirecting back to your homepage.
For that you'll need to add something like this after your submit function:
window.location.replace("index2.php");
Rather than using <meta http-equiv="refresh" content="0; url=http://myurl.com/" /> in index2.php, just add header("Location: http://myurl.com/"); at the end of the script instead of "success" or "invalid" message. Also remove any HTML before the PHP code starts to prevent errors like "Headers already sent, output started on line ..."

Perform two task with jQuery and php

I have a form which a user fills in, the data is sent to my email, but I also wanted email to be posted to my mail chimp using api but it's not working at the moment.
Here is my form:
<form method="POST" onsubmit="return false;" id="dealerForm ">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="subject" name="subject" value="Dealer partner message" type="hidden">
<input class="form-control" placeholder="Your Name *" id="name" name="name" required="" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Email *" id="email" name="email" required="" type="email">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Phone *" id="phone" name="phone" required="" type="tel">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Dearlership Info *" id="message" name="message" required=""></textarea>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-right">
<button type="submit" class="btn send_msg">Send Message</button>
</div>
</div>
</form>
Here is my php with mail chimp api and mail send.
<?php
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'myapikey'; // enter your MailChimp API Key
// ****
$mailchimp_list_id = 'mylistID'; // enter your MailChimp List ID
// ****
$subscriber_email = addslashes(trim($_POST['email']));
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Not a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$merge_vars = array();
require_once 'mailchimp/php/MailChimp.php';
$MailChimp = new \Drewm\MailChimp($mailchimp_api_key);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $mailchimp_list_id,
'email' => array('email' => $subscriber_email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => true,
));
if($result == false) {
$array['valid'] = 0;
$array['message'] = 'An error occurred! Please try again later.';
}
else {
$array['valid'] = 1;
$array['message'] = 'Success! Please check your mail.';
}
echo json_encode($array);
}
}
if (isset($_POST["email#mail.com"])) {
$to = 'mail#mail.com';
$subject = $_POST['subject'];
$message = 'Name: '.$_POST["name"].'<br>Email: '.$_POST["email"].'<br>Phone: '.$_POST["phone"].'<br>Message: '.$_POST["message"];
$headers = 'From: ' . $_POST["email"] . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .
'Content-type: text/html; charset=iso-8859-1;';
if(mail($to, $subject, $message, $headers)){
echo "New record created successfully";
}
}
?>
While my JQuery code:
$("#dealerForm").on("submit", function(){
//debugger;
$.ajax({
type: 'POST',
var url;
url: "contact/dealer.php",
data: $("#dealerForm").serialize()
}).done(function (data) {
//debugger;
console.log(data);
window.location.href = "https://example.com/Thank%20You.html";
});
$("#dealerForm")[0].reset();
return false;
});
Thanks for your comment and your help.
Before mail-chimp fix I think you need to fix followings:
You don't need to use onsubmit="return false;" in form declaration. You already returned false in jQuery onsubmit. And also remove space from form ID name. So, your form declaration can be like <form method="POST" id="dealerForm">
Remove var url; from ajax
Now debug email/mailchimp code in dealer.php.

call php file from javascript / Google recaptcha

Many apologies if the answer to my question is obvious.
I am trying to incorporate the Google reCaptcha into my website.
This is the javascript in the HEAD of my page:
var onSubmit = function(token) {
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
The reCaptcha is visible and working.
The above code gives me the result of 'success:' BUT is not processing the form using the call to the php file.
All other scripts on the page are working fine.
Here is the contact.php code:
I've made those changes to my code. No change in the result however. Here is the code for the php file:
<?php
//contact form submission code
//Validate data on the form
// define variables and set to empty values
$name = $email = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = contact_input($_POST["name"]);
$email = contact_input($_POST["email"]);
$message = contact_input($_POST["message"]);
}
function contact_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// if the url field is empty
if(isset($_POST['url']) && $_POST['url'] == ''){
// put your email address here
$youremail = 'my#email.co.uk';
// prepare a "pretty" version of the message
// Important: if you added any form fields to the HTML, you will need to add them here also
$body = "Contact Form from Wilderness Canoe website just submitted:
Name: $_POST[name]
E-Mail: $_POST[email]
Message: $_POST[message]";
// Use the submitters email if they supplied one
// (and it isn't trying to hack your form).
// Otherwise send from your email address.
if( $_POST['email'] && !preg_match( "/.+#.+\..+/i", $_POST['email']) ) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}
// finally, send the message
mail($youremail, 'Contact Form', $body, $headers );
}
?>
and the code for the form:
<form id="form" method="post" action="assets/php/contact.php" onsubmit="return validate();">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-account mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="name"> Full Name</label>
<input class="mdl-textfield__input " type="text" id="name" required name="name">
<!--error msg ><span class="mdl-textfield__error">Only alphabet and no spaces, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-email mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="email">Your Email</label>
<input class="mdl-textfield__input " type="text" id="email" required name="email">
<!--error msg ><span class="mdl-textfield__error">Valid email only, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-comment-text mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="message">Your Message/Comment</label>
<textarea class="mdl-textfield__input " type="text" rows= "1" max-rows="4" id="message" name="message"></textarea>
</div>
<!-- antispam --><p class="antispam">Leave this empty: <input type="text" name="url" /></p>
<!-- RECAPTCHA -->
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<div class="clear"><button type="submit" value="Send" name="submit" id="mc-embedded-contact" class="send">Submit</button></div>
</form>
The complete javascript:
<script type="text/javascript">
var onSubmit = function(token) {
var formData = $("#form").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
var onloadCallback = function() {
grecaptcha.render('mc-embedded-contact', {
'sitekey' : '6Ldbfg8UAAAAAAaWVBiyo4uGfDqtfcnu33SpOj6P',
'callback' : onSubmit
});
};
</script>
Your ajax request doesnt send any form data in your code. You should add your form data like this:
var onSubmit = function(token) {
var formData = $("#yourFormId").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};

How to redirect on button click using php

I am using a button on my form. I am trying to redirect to another page on button click after successful submission of user info. Every thing works properly except redirection. Here is the code I tried.
Html code:
<form role="form" id="contact-form" method="get">
<div class="form-group row">
<input type="email" id="email" name="email" placeholder="Enter your email" required="required" class="form-control input-lg" />
<input type="text" id="address" name="address" placeholder="Enter your address" required="required" class="form-control input-lg" />
<button type="submit" class="btn btn-t-primary">Show Me Now!</button>
</div>
</form>
Javascript code:
function contact() {
$("#contact-us-form").submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
form = $(this);
data = $(this).serialize();
$.post("contact.php", data, function(response){
form.trigger('reset');
});
}
Php code:
<?php
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
if (isset($_POST['email'])) {
$email = $_POST['email'];
$address= $_POST['address'];
$subject = "Message from: ".$email;
$content = "Email: " . $email."\n"
. "Address: " . $address;
$headers ='Reply-To: ' . $email . "\r\n";
mail('example#gmail.com', $subject ,$content, $headers );
header("Location:https://www.example.com");
echo 1;
}else {
echo 0;
}
?>
You can't redirect an ajax request from PHP, instead use this:
$(function() {
$("#contact-form").submit(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
form = $(this);
data = $(this).serialize();
$.post("contact.php", data, function(response) {
form.trigger('reset');
//Redirection
window.location.href = "https://www.google.com";
});
});
});
Just remove this header("Location:https://www.example.com"); from your PHP.
I hope this will help you.
Maybe you have to write the entire url when you are setting the header:
header("Location: http://www.google.com");
This isn't actually necessary.
Inside of the HTML form tag, add where you want to post the data to inside of the action attribute.
<form role="form" id="contact-form" method="get" action="postpage.php"> <!-- notice the action attribute !-->
Try this!
echo '<meta http-equiv=REFRESH CONTENT=0;url=./yourDestination.php>';
As we can see in the code, the page would refresh to the url you declared.
"Content = 0" means that it'll refresh after 0 seconds
You could modify the number if you want!
I wonder why you have set form method="get", but used $_POST variable under php code. Here's another version using POST method, try if it helps.
<?php
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
if (isset($_POST['email'])) {
$email = $_POST['email'];
$address= $_POST['address'];
$subject = "Message from: ".$email;
$content = "Email: " . $email."\n"
. "Address: " . $address;
$headers ='Reply-To: ' . $email . "\r\n";
mail('example#gmail.com', $subject ,$content, $headers );
header("location: https://google.com");
exit;
}
?>
<form role="form" id="contact-form" method="post">
<div class="form-group row">
<input type="email" id="email" name="email" placeholder="Enter your email" required="required" class="form-control input-lg" />
<input type="text" id="address" name="address" placeholder="Enter your address" required="required" class="form-control input-lg" />
<button type="submit" class="btn btn-t-primary">Show Me Now!</button>
</div>
</form>
You need to set the absolute address, including the protocol (https://) in your header location if you want to redirect to a new site.
header("Location: https://www.google.com")
Without the protocol, the location is assumed to be relative and will be appended to the existing domain.
Additionally, you should not echo anything after the headers.
First you have to write PHP code that handles Ajax Request:
if (isset($_POST['ajax_request'])) {
// write code;
echo "http://www.example.com"; // redirect url
}
Javascript:
jQuery(document).ready(function($) {
$.post('/path/to/file.php', {"ajax_request": true}, function(data, textStatus, xhr) {
window.location.href = data; // http://www.example.com
});
});
Hope this helps.

js not passing form data for php mail

I'm a beginner attempting to create a HTML webpage. I'm using a free online template and trying to create a Contact Page. The contact calls a php script to send an email of the captured fields. I can get this to work when I send the email as pure php with no javascript or ajax. However when I try to use the javascript with the ajax code, the contents of the web form are not being passed. Two near identical issues have been raised here but I am finding the javascript to complicated for myself to understand as a beginner. The slight differences in the js has resulted in hours of trying to resolve without success.
js deleting submitted form data
PHP form post data not being received due to jQuery
The HTML code is
<div class="col-md-4 col-sm-12">
<div class="contact-form bottom">
<h2>Send a message</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Id">
</div>
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Your text here"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
The PHP script is called sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$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 = 'email#email.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;
The javascript is as follows
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $.post(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contacting us. We will reply as soon as possible.</p>').delay(3000).fadeOut();
});
});
There are two issues, the first being that the form data doesnt pass when using the javascript code. The second is that it displays the message twice and sends two emails. I think the second issue is related to the php script calling the function again.
Help & guidance will be really appreciated, I am a beginner only attempting a small challenge.
The mail form appears to be deliberately disabled. It took me a while to fix it.
The code below will make it work. I hope this helps.
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contacting us. We will reply as soon as possible.</p>').delay(3000).fadeOut();
});
});

Categories

Resources