Why is this ajax call to the correct php script not returning anything?
I have this AJAX:
function sendMail () {
$.post('php/sendMail.php', function(result){
alert(result);
})
}
$('#submitContact').click(function(){
sendMail();
})
and this PHP:
<?php
$trimmed = array_map('trim', $_POST);
$message = $trimmed['message'];
$email = $trimmed['email'];
$name = $trimmed['name'];
if (empty($message)) {
$message = FALSE;
}
if (empty($email)) {
$message = FALSE;
}
if (empty($name)) {
$message = FALSE;
}
if ($message && $email && $name){
$body = "From: $name.\n \n $message";
mail(/*some email*/, 'Website Contact Form Submission', $body, "From开发者_开发百科: $email");
echo ('success');
}
echo($message.' '.$email.' '.$name);
?>
All the html elements defined exist. When I run it all that returns is a blank alert box (meaning that the PHP script did not print out success). Any idea why it is not sending the mail?
You don't appear to be sending any data with your POST
.
If you're trying to submit a form, try this:
$.post('php/sendMail.php',$('form').serialize(), function(result){
alert(result);
})
Edit: As Tomalak rightly points out in the comments, you'll need to specify which form you are serializing. I'd normally give the form an id
and use that:- $('#myform').serialize()
You're not sending any data to that URL.
The reason you are seeing an empty alert box is because $email
and $name
is empty because you didn't pass any $_POST
variable.
And $message = FALSE
is blank when you echo it.
Try changing this line
echo($message.' '.$email.' '.$name);
To
var_dump($message.' '.$email.' '.$name);
And you'll see the value of $message.' '.$email.' '.$name
.
Any idea why it is not sending the mail?
Put simply, you didn't ask it to.
The syntax for $.post
is:
jQuery.post( url, [data,] [success(data, textStatus, jqXHR),] [dataType] )
The way jQuery works, you may skip the data
argument and still provide the following ones, but in this case you're simply not passing any data for your PHP script to work with.
Assuming that #submitContact
is a button in the form that you want to submit, you should serialise that form's contents and send that as the POST
data:
function sendMail($form) {
$.post('php/sendMail.php', $form.serialize(), function(result) {
alert(result);
});
}
var $btn = $('#submitContact');
var $frm = $btn.parents('form');
$btn.click(function() {
sendMail($frm);
});
The documentation is your friend. Use it.
(Note: The $
at the start of some of my variables is deliberate; it's a personal choice that jQuery objects have names starting with $
in my code.)
精彩评论