$.post does not submit data
$("#contact-us-form").submit(function () {
var nameVal = $("input[name=name]").val();
var companyVal = $("input[name=company]").val();
var titleVal = $("input[name=title]").val();
var emailVal = $("input[name=email]").val();
var phoneVal = $("input[name=phone]").val();
var messageVal = $("input[name=message]").val();
alert(nameVal);
alert(emailVal);
$.post("/mailer.php", {
name: nameVal,
company: companyVal,
title: titleVal,
email: emailVal,
phone: ph开发者_如何学GooneVal,
message: messageVal
}, function (data) {
alert("Data Loaded: " + data);
$('#thanks').show();
});
});
mailer.php in in root, and it contains:
<?php
if(isset($_POST['submit'])) {
$to = "myemail@domain.com";
$subject = "Inquiry";
$name = $_POST['name'];
$company = $_POST['company'];
$title = $_POST['title'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$body = <<<HEREDOC
From: $name
Company: $company
Title: $title
E-Mail: $email
Phone: $phone \n
Message: $message
HEREDOC;
mail($to, $subject, $body);
}
?>
I see the name and email alerts with correct data, but the data alert is empty, just shows Data Loaded:, so I'm guessing that the data is not submitted correctly.
How do I fix it?
Many thanks!
The 'data' callback is what the form you're posting to responds with. So, its contents depend on what mailer.php is supposed to respond with.
EDIT: There's no 'echo/print' in mailer.php, so there's no way for you to know if the mailing succeeded. Besides the fact that you're not sanitizing the content, or checking for a valid email address, you should echo a basic successs or true or false message at the end, so you can tell your JavaScript what to do.
So, something like
$result = mail($to, $subject, $body);
if($result)
echo 'success';
Then, in your js callback
if(data=="success")
{
$('#thanks').show();
}
else{
$('#error').show();
EDIT #2: Does the Submit input element actually have the name 'submit'? It's possible you're just failing that isset() check every time.
Just added return false; and it worked! :)
Looks like mailer.php isn't responding with anything. It looks like it's sending an email, so that's why data is empty. The fact that the post callback does fire shows that the data was sent to mailer.php.
You can use the second argument of the callback to check:
, function (data, textStatus) {
alert("Data Loaded: " + textStatus);
$('#thanks').show();
or the exact same thing using the arguments array:
, function () {
alert("Data Loaded: " + arguments[1]);
$('#thanks').show();
If you want data to actually contain something, then you can output the subject in mailer.php like:
...
echo $subject;
mail($to, $subject, $body);
Now alert(data) should work.
Also, be sure to prevent the default submit of the form, so the page doesn't change while this is happening:
$("#contact-us-form").submit(function (event) {
event.preventDefault();
...
加载中,请稍侯......
精彩评论