I cant understand why the following is not working, I am trying to call a php script to send an email, but i dont think my ajax call is calling the php script at all, I just get an error returned.
My ajax call:
var name_field = $('#cf_name').val();
$.ajax({
type: 'post',
url: 'contact.php',
data: {'name_field' : name_field },
dataType: 'json',
success: function(data) {
if(data.status == 'success')
alert("Thank you for subscribing!");
else if(data.status == 'error')
alert("Error on query!");
},
error: function(err) {
alert(err.responseText);
}
});
My php script:
$field_name = isset($_POST['name_field']);
$field_email = 'name#email.com';
$field_phone = '12345';
$field_message = 'Hello World!';
$mail_to = 'emailaddress#email.com';
$subject = 'Message from a website visitor '.$field_name;
$body_message = 'This message has been sent via website:'."\n\n";
$body_message .= 'From: '.$field_name."\n\n";
$body_message .= 'E-mail: '.$field_email."\n\n";
$body_message .= 'Phone Number: '.$field_phone."\n\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) {
$response_array['status'] = 'success';
}
else {
$response_array['status'] = 'error';
}
header('Content-type: application/json');
echo json_encode($response_array);
If i navigate to the url directly the php works as intended, but i can not get the ajax post to call it.
$field_name is not an actual string, it's a boolean since you used $field_name=isset($_POST[name_field']). Remove the isset().
See this: jQuery Ajax post cancelled i'm not a js expert but I agree with your problem being the async execution of your ajax call, since it takes a while to send an email, maybe isn't completed in time for your js
See this nice explanation about the "async" propertie in the ajax call:
What does "async: false" do in jQuery.ajax()?
And see this question/answer:
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
You should check url: contact.php as you did not specify the full URL, so your post is going to a relative path. The root path will be same current script path.
Related
I need to send email asynchronously.
For that I have a jQuery ajax client and PHP backend to actually send eMail, still AJAX's success method is not being called. I understand it is simple, but yet doesn't seem to be working. Can somebody please take a look at my code and see what I'm doing wrong? Really appreciate it.
$.ajax({
type: "POST",
url: "mail.php",
data: {name: "manu", email: "abc#abc.com"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('mail sent');
$('#divToBeWorkedOn').html(msg);
}
});
and I have mail.php
<?php
header("Content-type: application/json");
$name = trim($_POST['name']);
echo $name
$email = trim($_POST['email']);
$msg="my email";
$emailTo = 'myemail#gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $message";
$headers = 'From: Saddi website <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
echo 1;
?>
I see 2 problems.
you're echoing just 1, its not JSON. So in your PHP code do json_encode("msg"=>"1");
In my experience, if you have this
header("Content-type: application/json");
OR header("Content-type: json/text");
You won't get any result in jquery success or error blocks.
success: function(msg) {
alert(msg);
}
the msg would return null value (or nothing). The alert will happen but will show something like object object.
I'm making a simple contact form, I have an old school php mailer mail.php and a jQuery front page from where I'm calling it.
As I wanted it to work, it should've stayed on same page, but it actually jumps to mail.php and displays the message
Thank you for contacting me. I'll try to reach you ASAP.
Though it does send the mail, thats still not acceptable as that was not my intention. Can anybody find out what I'm doing wrong here ?
Any help appreciated.
PHP:
<?php
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
$emailTo = 'myEmail#gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $message";
$headers = 'From: Saddi website <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
echo "Thank you for contacting me. I'll try to reach you ASAP.";
return true;
?>
FORM (Lot of bootstrap tags there, so to keep it clean I'm just posting ):
<form class="form" action="mail.php" method="post" id="contact-form">
</form>
And here goes my AJAX:
var data_string = jQuery('#contact-form').serialize();
jQuery.ajax({
type: "POST",
url: "mail.php",
data: {name:name,email:email,message:message},
timeout: 6000,
error: function(request,error) {
if (error == "timeout") {
jQuery('#timedout').fadeIn('slow');
setTimeout(function() {
jQuery('#timedout').fadeOut('slow');
}, 3000);
}
else {
jQuery('#state').fadeIn('slow');
jQuery("#state").html('The following error occured: ' + error + '');
setTimeout(function() {
jQuery('#state').fadeOut('slow');
}, 3000);
}
},
success: function() {
jQuery('span.valid').remove();
jQuery('#thanks').fadeIn('slow');
jQuery('input').val('');
jQuery('textarea').val('');
setTimeout(function() {
jQuery('#thanks').fadeOut('slow');
}, 3000);
}
First i will recommend you to use jQuery Form Plugin, very helpful for this kind of ajax post and validations.
jQuery Form
Second, you can use event.preventDefault(); to avoid the default action of the link but it will really depend on how are you triggering your form to the ajax code
event.preventDefault
I have a site running on Windows Azure that contains a simple contact form for people to get in touch. Unfortunately, that form isn't work right now...
I have an index.php file that contains the form:
<div class="form">name="name" placeholder="Name" id="contactname" />
<input type="text" name="email" placeholder="Email" id="contactemail" />
<textarea name="message" placeholder="Message" id="contactmessage"></textarea>
<button>Contact</button>
</div>
I then have a JS file like this:
if ($('#contact').is(":visible")) {
$("#contact button").click(function() {
var name = $("#contactname").val();
var message = $("#contactmessage").val();
var email = $("#contactemail").val();
var emailReg = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$/;
// client-side validation
if(emailReg.test(email) == false) {
var emailValidation = false;
$('#contactemail').addClass("error");
}
else
$('#contactemail').removeClass("error");
if(name.length < 1) {
var nameValidation = false;
$('#contactname').addClass("error");
}
else
$('#contactname').removeClass("error");
if(message.length < 1) {
var messageValidation = false;
$('#contactmessage').addClass("error");
}
else
$('#contactmessage').removeClass("error");
if ((nameValidation == false) || (emailValidation == false) || (messageValidation == false))
return false;
$.ajax({
type: "post",
dataType: "json",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html('<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>');
}
});
return false;
});
};
and finally, a php file to send the email called send-email.php:
$destination = 'info#clouddock.co'; // change this to your email.
// ##################################################
// DON'T EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING
// ##################################################
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$subject = $name;
$headers = "From: ".$name." <".$email.">\r\n" .
"Reply-To: ".$name." <".$email.">\r\n" .
"X-Mailer: PHP/" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
mail($destination, $subject, $message, $headers);
}
When I fill in the contact form, the JS validation appears to be working, and when I click send the 'Thanks for getting in touch...' text appears, as if the message has been sent. But I don't receive any email. Can anyone advise as to where the problem might be? Could it be Azures configuration blocking the messages from being sent out?
You are using $("#contact").serialize() to get data to send but you've got no elements with ID contact.
You should use $("#contactname, #contactemail, #contactmessage").serialize() (and fix first input ;) ).
And always validate input data in PHP, not only in JS!
Of course it will display the thanks message, all it needs is a response back from the server. What you need is to test whether the mail actually sent or not, then return that back to your original script to determine what message to show.
if(mail($destination, $subject, $message, $headers)) {
return '<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>';
} else {
return '<p class="fail">The e-mail failed to send.</p>';
}
And then set your AJAX to:
$.ajax({
type: "post",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html(data);
}
});
You'll probably find that you get the fail message, and that could well be the setup of your server, or it could be you not passing the right thing to the mail() function. You then need to debug your script to find out whether the right information is being passed etc.
With Windows servers they need to be configured to pass all mail from the mail() function to an SMTP server, so if that's not been done on your Azure server then your mail will instantly fail.
I've been looking all over StackOverflow and other forum sites, but I still don't know how to acomplish what I'm doing.
I want to send personalized emails (can be text or html) in a website I'm developing.
I'm using ajax to send the list of mails, the subject and the body. The code looks like this
This is the .js
function loadsentmail(){
var subject = document.getElementById("subject_title").value;
var content = tinyMCE.get('content').getContent();
var from = "somemail#mail.com";
var body = new Array();
body[0]=content;
$.ajax({
type:'POST',
url:'sendmail.php?mails='+mails+'&names='+names+'&idgroup='+idGrupo+'&subject='+subject+'&body='+body+'&from='+from+'&flag=1',
data: {},
success:function(result){
alert("Mail sent correctly");
},
error:function(){
alert("Mail was not sent");
}
});
}
This is the .php
$to = $_GET['mails'];
$names = $_GET['names'];
$subject=$_GET['subject'];
$from = $_GET['from'];
$body = $_GET['body'];
$flag=$_GET['flag'];
$groupId=$_GET['idgroup'];
echo $flag;
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: Some Company <somemail#somemail.com>\r\n";
$headers .= "Reply-To: somemail#somemail.com\r\n";
$headers .= "Return-path: somemail#somemail.com\r\n";
$headers .= "Cc: somemail#somemail.com\r\n";
$headers .= "Bcc: somemail#somemail.com\r\n";
switch($flag)
{
case 1:
if (mail($to, $subject,$body,$headers)) {
echo("<p>Message successfully sent!</p>");
}
else {
echo("<p>Message delivery failed...</p>");
}
break;
}
So far so good, I tested with small body, and it worked, but once I pasted a big html file, I got the following error
<h1>Request-URI Too Large</h1>
<p>The requested URL's length exceeds the capacity
limit for this server.<br />
</p>
What is the best practice to send a big Body from a .js to a .php?? I've search a lot throughout the internet but I still can find an answer. Please help me :S
$.ajax({
type:'POST',
url:'sendmail.php',
data: {
mails: mails,
names: names,
idgroup: idGrupo,
subject: subject,
body: body,
from: from,
flag:1
},
type: "POST",
success:function(result){
alert("Mail sent correctly");
},
error:function(){
alert("Mail was not sent");
}
});
Post will allow the larger data set and with jquery ajax you should send the data using the data object even if you use GET.
Also I believe (I'm a perl not a php dev so you will need to look this up) you will need to change your php to grab from the Post obj.
$to = $_GET['mails']; will become $to = $_POST['mails']
I'm having this problem. Look at this: http://santz.net/index.contacto.html
Try sending whatever and see what happens (it's mine, I recieve it, send whatever no problem...). (It leaves the page, shows a dialog that says thanks for contacting us... and it redirects you to the same page). I HATE THIS!!!
I'm looking fore some AJAX and jQuery code that after the message is sent, it clears the form and opens a dialog (the common one... like the typical loggin boxes) and that fades the page and that show some "x" content...
The thing is that I don't know how to do any of this things and I'm driving crazy! If you could give me the code and tell me where to put it or just give a tutorial for noobs or something like that it would be great...
I leave here the PHP code I'm using:
<?php
$field_name = $_POST['php_name'];
$field_email = $_POST['php_email'];
$field_phone = $_POST['php_phone'];
$field_message = $_POST['php_message'];
$field_sender = 'alpha#hotmail.com';
$mail_to = 'gama#hotmail.com.ar';
$subject = 'Mensaje via Santz.net de '.$field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Phone: '.$field_phone."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_sender."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Gracias por contactarse, en breve, me pondre en contacto.\n\nSantz Design | www.santz.net');
window.location = 'index.contacto.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('El envio fallo. Por favor, envie un mail directamente a info#santz.net');
window.location = 'index.contacto.html';
</script>
<?php
}
?>
Try change this:
window.location.assign('http://www.santz.net/');
instead of:
window.location = 'index.contacto.html';
Showing error message on the same page, follow this example:
Add validation message in fieldset instead of js popup
And for a modal windows, use a plugin like this one:
http://www.mywebdeveloperblog.com/my-jquery-plugins/modalpoplite
Demo:
http://www.mywebdeveloperblog.com/projects/modalpoplite/demo/
saludos ;)
Why dont you use jQuery
$('input[type="submit"]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: contact.php,
data: $('#contact-form"').serialize();,
success: function() {
//modal
}
});
});
something along those lines would be the ajax way of submitting your form and then pop up a window to the user saying thanks please view my form to get an idea just without popup