I am using ajax to submit a form using swiftmailer. I'm getting an error when I try to submit the form. I think it has something to do with the "data" setting in the ajax call. I can get the swiftmailer mailing script to work fine when submitting a form not using ajax. You can see my work here, http://wickbuildings.com/form. I'm stuck and any help would be appreciated!
Here is my javascript:
$(document).ready(function () {
$("button#send_btn").click(function(){
$.ajax({
type: "POST",
url: "/assets/js/mailers/become-a-builder.php",
data: $('form[name=BecomeBuilderForm]').serialize(),
success: function(msg){
$("#thanks").html(msg) //hide button and show thank you
$("#form-content").modal('hide'); //hide modal
},
error: function(){
alert("failure");
}
});
});
});
and my swiftmailer mailing script:
<?php
//grab named inputs from html then post to #thanks
if (isset($_POST['name'])) {
$email_dsm = strip_tags($_POST['email_dsm']);
$name = strip_tags($_POST['name']);
$business_name = strip_tags($_POST['business_name']);
$address = strip_tags($_POST['address']);
$city = strip_tags($_POST['city']);
$state = strip_tags($_POST['state']);
$zip = strip_tags($_POST['zip']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$comments = strip_tags($_POST['comments']);
// create message that fills #thanks container
echo "<div class=\"alert alert-success\" >Thank you for your inquiry. " . $email_dsm . " will be following up with you shortly.</div>";
// Create message of email to recipient
$body = "the contents of the email here";
require_once '../plugins/swiftmailer/swift_required.php';
// Create the mail transport configuration
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
'user#somedomain.com'
));
$message->setSubject('my email subject here');
$message->setBody($body, 'text/html');
$message->setFrom($Email);
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
}
?>
Forms don't need names. give it an ID.
<form id="BecomeBuilderForm">
then use:
$('#BecomeBuilderForm').serialize()
or if you really want to use the name add double quotes around BecomeBuilderForm
$('form[name="BecomeBuilderForm"]').serialize()
if you really get stuck make sure your form is serializing using console.log()
$(document).ready(function () {
$("button#send_btn").click(function(){
console.log($('form[name="BecomeBuilderForm"]').serialize());
});
});
Related
I'm trying to create a form to send mail using ajax and jquery, so I have a php and javascript script however when I try to send mail from my form nothing happens, Do you have a solution ? my ajax script initially allows not to reload the page when the email is sent my data variable retrieves each ID of my form ajax send data back to php script giving a positive or negative answer here it doesn't send any answer, the php script retrieves the data and transmits it directly to the host's email address (ovh)
here my ajax script
$('#send_email').click(function(e){
e.preventDefault();
var data = {
email: $('email').val(),
name: $('name').val(),
objet: $('firstname').val(),
message: $('message').val()
};
$.ajax({
url: "mail.php",
type:'POST',
data: data,
succes: function(data){
$('#js_alert_succes').css({'display' : 'block'});
setTimeout(function(){
$('#js_alert_succes').css({'display' : 'none'});
$('#email').val("");
$('#name').val("");
$('#object').val("");
$('#message').val("");
}, 3000);
},
error: function(data) {
$('#js_alert_danger').css({'display' :'block'});
setTimeout(function(){
$('#js_alert_danger').css({'display' : 'none'});
$('#email').val("");
$('#name').val("");
$('#object').val("");
$('#message').val("");
}, 3000);
}
});
});
and here my php script
<?php
if($_POST){
$firstname = $_POST['firstname'];
$email = $_POST['email'];
$name = $_POST['name'];
$object = $_POST['objet'];
$message = $_POST['message'];
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: $name <$email>\r\nReply-to : $name <$email>\nX-Mailer:PHP";
$subject="$objet";
$destinataire="postmaster#arrowsecurite.com";
$body="$message";
if(mail($destinataire,$subject,$body,$headers)) {
$response['status'] = 'success';
$response['msg'] = 'votre email est envoyé';
} else {
$response['status'] = 'error';
$response['msg'] = 'votre email na pas été envoyé';
}
echo json_encode($response);
}
?>
don't know if you solved your problem, but for debugging press F12 and open Network tab, to see what your PHP code returns after you submit your form. And in PHP code i would recommend return json_encode($response);
Im using pop3 php mailler and ajax. There is no problem for sending mail but when I press sent mail button it incease number of mails. So whats the problem
my ajax code :
$("button").click(function(e){
$('.alert').slideUp(100);
e.preventDefault();
var dataArray = $("form").serialize();
$.ajax({
type: "POST",
url: "include/login.php",
dataType: "json",
data: dataArray,
success: function (data) {
if(data.result == "true"){
$('.alert').removeClass('alert-danger').addClass('alert-success').slideDown(200);
$('.alert strong').html("hello "+data.name);
setTimeout(function(){
window.location.replace("<?php if(isset($_SERVER['HTTP_REFERER'])) { echo "$_SERVER[HTTP_REFERER]";}else{echo "index.php";} ?>");
}, 1200);
}else if(data.result == "false"){
$('.alert').removeClass('alert-success').addClass('alert-danger').slideDown(200);
$('.alert strong').html(data.name);
}else if(data.result == "warning"){
$('.alert').removeClass('alert-warning').addClass('alert-danger').slideDown(200);
$('.alert strong').html(data.name);
/// send mail button click
$('body').on('click','#activation',function(e){
e.preventDefault();
$.ajax({
beforeSend:function(){
$('.alert strong').html("sending mail..");
},
url:"include/activation_mail.php",
type:"post",
data:{u_id:data.userid,u_pass:data.u_pass},
success:function(msj){
$('.alert').removeClass('alert-danger').addClass('alert-success').slideDown(200);
setTimeout(function(){
$('.alert strong').html(msj);
},1000);
},
});
});
}
},
});
});
mailing php :
$sql = "UPDATE users SET u_activation_code = '$activation_code' WHERE u_id = '$u_id'";
$query = mysqli_query($con,$sql);
if($query){
$sql="SELECT * FROM users WHERE u_id='$u_id'";
$query = mysqli_query($con,$sql);
$row = mysqli_fetch_row($query);
$id = $row[0];
$name = $row[1];
$surname = $row[2];
$fullname = "$row[1] $row[2]";
$username = $row[5];
$email = $row[6];
$icerik = "aktivasyon maili <a href=''>activation</a>";
$mail = new PHPMailer();
$mail->CharSet='utf-8';
$mail->setFrom('fragman#aktivasyon', 'Aktivasyon');
$mail->addReplyTo('mymail#gmail.com', 'activation');
$mail->addAddress($email,$fullname);
$mail->Subject = 'activation link';
$mail->AltBody = 'This is a plain-text message body';
$mail->Body = "click active <a href=''>clicked</a> ";
//send the message, check for errors
if (!$mail->send()) {
echo "error sending: " . $mail->ErrorInfo;
} else {
echo "send mail";
}
}else{
echo "error query";
}
where is problem ?
Because of this line:
$('body').on('click','#activation',function(e){
On every click on a button, you're binding another click event to #activation making it run multiple times on every click on that button. You should bind the click event ONCE.
You could also do:
$('body').off('click','#activation');
And then bind the click event again, to prevent it from happening.
EDIT
You're binding a click event for every BUTTON element existing in the DOM:
$("button").click(function(e){
I also suggest that you specify this event to a button with unique ID, and not for every button. Because when you click on the #activation button, it will ALSO trigger the call to the login ajax (Since it's also a button element)
What you should do is to add an ID attribute to the button that when you click on trigger the login ajax:
<button id="login-btn">Log In</button>
And then, change the above binding to:
$("#login-btn").click(function(e){ // INSTEAD OF THE CURRENT $("button").click(function(e){
So I submit my form with Ajax like so
$("#submitform").click(function(e){
e.preventDefault();
var form_data = $("#contactfrm").serialize();
$.ajax({
type: "POST",
url: "/ltlcreation-new/wordpress/wp-content/themes/LTLCreation/includes/form-handler.php",
data: form_data,
error: function(){
alert("failed");
},
success: function(json_data){
console.log(json_data);
alert("success");
},
})
});
In my form-handler.php i catch the from errors
<?php
if(isset($_POST['submit'])) {
//include validation class
include 'validate.class.php';
//assign post data to variables
$name = #($_POST['name']);
$email = #($_POST['email']);
$message = #($_POST['message']);
$phone = #($_POST["phone"]);
//echo $name, $email, $message, $phone;
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($message, "message", 5, 1000);
$v->validateStr($phone, "phone", 11, 13);
if(!$v->hasErrors()) {
$to = "lukelangfield001#googlemail.com";
$subject = "Website contact form ";
$mailbody = $message . "\n" . "from " . $name . "\n" . $phone;
$headers = "From: $email";
mail($to, $subject, $mailbody, $headers);
echo "success";
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
//$nameErr = $v->getError("name");
//$emailErr = $v->getError("email");
//$messageErr = $v->getError("message");
//$phoneErr = $v->getError("phone");
echo $message_text; echo $errors;
$output = array($message_text);
echo json_encode($output);
}//end error check
}// end isset
These errors usually look like something like this
There were 4 errors sending your message!
Name must be at least 3 characters long.
Please enter an Email Address.
Message must be at least 5 characters long.
Phone must be at least 11 characters long.
["There were 4 errors sending your message!\n"]
I've tried to jSon encode the output and the in the success in ajax pull the json data out, however it just keeps returning an empty string like so
(an empty string)
My question is can you send data back from PHP to Ajax, if so I am doing this completely wrong?
You can output anything other than the json string so echo "success"; would make t. Use your debuggers Network response output tab to see that this is properly encoded.
Also don't use
$name = #($_POST['name']);
use instead
$name = isset($_POST['name']) ? $_POST['name'] : '';
If you still have a blank page make sure you have display errors set.
error_reporting(E_ALL);
ini_set('display_errors', 1);
I am an idiot I still had this in my PHP file which means the form wasn't firing or returning a response, silly me, glad i finally figured it out though
if(isset($_POST['submit'])) {
Thanks for the help guys
Here is an example of an Ajax contact form you can use:
Ajax.js
$(document).ready(function(){
$("#btn").click(function(){
var username=$("#name").val();
var email=$("#email").val();
var dis=$("#dis").val();
var process=true;
if(username=="")
process=false;
if(email=="")
process=false;
if(dis=="")
process=false;
if(process){
var dataString="name="+username + "&email="+email+ "&message="+dis;
$("#res").html('<span>Sending...</span><img src="a.gif">');
$.ajax({
url:"b.php",
type:"POST",
data:dataString,
success:function(data){
document.getElementById("name").value='';
document.getElementById("email").value='';
document.getElementById("dis").value='';
$("#res").html(data);
}
});
}else{
alert("fill all fields");
}
});
});
and b.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajax") || die("erro");
if(isset($_POST['name'])){
mysql_real_escape_string(htmlentities($name=$_POST['name']));
mysql_real_escape_string(htmlentities($email=$_POST['email']));
mysql_real_escape_string(htmlentities($message=$_POST['message']));
if(!empty($name) && !empty($email) && !empty($message)){
if(mysql_query("INSERT INTO `users` (name,email,message) VALUES('$name','$email','$message') ")){
echo 'The massage has been send';
}else{
echo mysql_error();
}
}
}
?>
enjoy that....
You have the following:
success: function(json_data){
While json_data is simply nothing. It should be
success: function(data){
I know I can use the form validation plugin with jQuery UI but for the sake of teaching myself some new tricks I'm taking this approach.
I have a jQuery script that posts a form to a PHP script via Ajax. The script then validates the input and sends a JSON encoded string back to the script. At this point, based on the status a validation message should be placed into a modal dialog and then opened to tell the user what happened.
Issue
It seems the script is returning a "null" status. In Chrome's JavaScript console the following line appears after clicking on the submit button of the form:
Uncaught TypeError: Cannot read property 'status' of null
Here's my validate_form.js
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.status > 0){
$("#response").dialog({
autoOpen: false,
modal: true,
height: 240,
width: 320
});
$("#response").dialog("open");
};
}
});
});
});
And here is contact.php
<?php
if(isset($_POST['contact_submit'])){
$name = trim($_POST['contact_name']);
$name = ucwords($name);
$email = trim($_POST['contact_email']);
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim($_POST['contact_notes']);
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("status"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("status"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$to = "info#mydomain.com";
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("status"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("status"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
}
echo json_encode($resp);
?>
UPDATE 1
Adding console.log(dataString); yields the following in the console:
contact_name=Test&contact_email=testaccount%40mydomain.com&contact_dept=general&contact_notes=this+is+a+test+
As you can see it should've failed on the notes not being between 25 and 500 characters and returned the proper error message. Instead I still see the "cannot read property 'status' of (null)"
UPDATE 2
Here is exactly what I see in the JavaScript Console
UPDATE 3
I decided to remove the prevent default and actually post directly to the contact page through a traditional <form> statement that includes the method="post" action="contact.php" to see if the script itself was properly generating the JSON string and it is; here's what it generated on my most recent test:
{"status":4,"message":"Comments must be between 25 and 500 characters"}
So either it's not sending it back to the ajax handler or something else is missing.
UPDATE 4
I modified the script to handle a null value and alert me if no value was passed. So it's obvious now that the script isn't passing a json string back to the ajax call even though in update 3 I've verified that it's echoing one to the screen. I'm at a loss... (Update script above)
UPDATE 5
So I've made some progress. It turns out that the null was being returned because in my PHP script I was checking if the submit button was set and part of the $_POST array. But, because I'm preventing the default action of the form through jQuery it's not being passed. Only the form values that are serialized are being sent in the dataString. So now I'm getting the errors back in the console that I expect but I'm not getting the modal dialog to show up. The drama continues.
Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
As noted you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.
Below i've mentioned some points try this to sort out your problem
1.change your method to get and try.
2.put die() after last echo and check what the exactly output.
So after more hours tweaking, testing, and pulling my hair out, here's the working script.
jQuery
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.err > 0){
var $response = $("<div></div>")
.dialog({
resizable: false,
autoOpen: false,
modal: true,
height: "auto",
width: "auto",
buttons: { "ok": function() { $(this).dialog("close"); } }
});
$response.html("Error:");
$response.html(data.message);
$response.dialog("open");
$(".ui-dialog-titlebar").hide();
};
}
});
});
});
And for the PHP script I had to tweak it slightly as well to process it properly.
<?php
$name = trim(urldecode($_POST['contact_name']));
$name = ucwords($name);
$email = trim(urldecode($_POST['contact_email']));
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim(urldecode($_POST['contact_notes']));
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("err"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($email_pattern, $email)){
$resp = array("err"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("err"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("err"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("err"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("err"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
echo json_encode($resp);
?>
Everything works perfectly, modal alerts and all to the user. Thanks to those who attempted to help!
So I've read the jQuery AJAX pages, and a bunch of tutorials, but am having a slight problem over here.
There are no errors, or warnings, just a blank page.
I am trying to send an email when the user fills in the newsletter subscription test field with their email address, and when you click submit, the page refreshes! (1st problem) and it fails to display anything on the page (second problem), all you see is just a blank page. No emails were received.
I've tested the email script separately, which works fine. I've been using for months with different sites so I know it works.
I've tried changing things around in jQuery etc but nothing has helped fix this problem.
jQuery:
$(function () {
var txt = $('.email').val();
$.ajax({
url: 'index.php',
type: 'post',
data: {
email: txt
},
success: function (data) {
alert(data);
},
error: function (err, req) {
$('#Response').html({
"Somethin' got broked. Please try again."
});
}
});
});
PHP:
<?php
if($_POST["email"] != null)
{
require_once "Mail.php";
$email = $_POST["email"];
// Send it.
$from = "X#X.com.au";
$to = $email;
$subject = "Newsletter Subscription Request.";
$body = "Thank you for subscribing to our newsletter!";
$host = "mail.X.com.au";
$username = "no-reply#X.com.au";
$password = "X";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
}
?>
HTML:
<h4 id="Response">Stay informed. Subscribe to our Newsletter!</h4>
<form class="newsletterForm" action="index.php" method="post">
<input type="text" class="email" name="email" />
<input type='submit' class="btn" value="Subscribe" />
</form>
Can someone please help me figure out why this won't work?
Thank you
The 1st thing I do when stuff like this isn't working is to watch the page calls in the Chrome Developer Tools window.
As far as your code goes, the reason the page is refreshing is because the form submit is going through. To keep that from happening, you have to trap the form submit:
$("form").submit(function() {
// Do ajax
return false; // Keeps the form from submitting
});
Once you have that in place, you should be getting better results.
I would caution, however, that it is much easier to get the PHP email sending form working without using ajax at first by just having it handle the regular form submit. Once that works, then tie in the ajax on top of it.
With the following line you suppose to receive an answer from the PHP Script
success: function(data) {
alert(data);
}
But in the PHP script you don't output anything...Try writing something like
//[...]
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
die(1);
please try this surely you can get the problem solve.
function FormSubmit()
{
$.ajax({
type: "POST",
url: 'index.php',
data: $("#form_main").serialize(),
async: false
}).done(function( data ) {
$("#Response").hide();
if (isNaN(data))
{
dispmsg = "<div class='alert alert-danger' role='alert'>Oops..Something had gone wrong! Please try again!</div>";
$("#assess_me_response").html(dispmsg);
setTimeout('ResetForm();',3000);
}
else
{
dispmsg = "<div class='alert alert-success' role='alert'>Thank you for sharing the details. Our Consultant will contact you shortly!</div>";
$("#assess_me_response").html(dispmsg);
setTimeout('Redirect();',3000);
}
return true;
});
}
make your php as this..
<?php
$to = "xxxx#some.com";
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
$phone = $_POST['phone'];
$subject = "Entry received";
$msg = "\n Name:" . $name . "\n Email id:" . $email ."\n Age:". $age . "\n Contact number: " . $phone;
$headers = "From:xxx#yyy.com";
mail($to,$subject,$msg,$headers);
echo "<div align='center'>Thank you " . $name . "!, we will contact you shortly.</div>";
?>
try this you can solve.