在尝试发送电子邮件时,无法让PHP文件与JQuery正常交互

I have a page I wrote mostly using JQuery and at the end I want to send an email with the results from the page. I have this code in my script:

index.html

var myUrl = "http://mywebsite/mail.php";
$.ajax({
       type: "POST",
       url: myUrl,
       cache: false,
       contentType: "application/json; charset=utf-8",
       data: {  body:"test",
                to:"myemail@gmail.com",
                subject:"Test Results"
             },
       dataType: "json",
       complete: function(transport, data){  
                    console.log(data);
                    if (transport.status == 200) 
                        alert("Worked.");
                    else 
                        alert("Didn't work, " + transport.status); 
                }
   });

I know that I have the right path for my .php file because if I change the 'myURL' variable I get an error. Here is my other file:

mail.php

<?php

$body = $_POST['body'];
$to = $_POST['to'];
$subject = $_POST['subject'];

mail($to, $subject, $body);
?>

The problem is that while my jquery is returning the alert "Worked", and it seems like everything is working, my mail.php file doesn't seem to ever run: I don't see any of the console logs that I have there appear, while the console log in my index file does appear. I also don't get the email, but no errors appear. I even tried putting errors in on purpose in the .php file but nothing happened. I think this is some kind of small issue because I've never really used php before, so hopefully the issue is something simple.

--EDIT-- So I updated my code, I'm no longer seeing the console.logs in my index.html file for some reason even though they were showing earlier. It would be great if I could get an answer on whether I should be using $.post or $.ajax, and also I am still looking for a way to confirm that the mail command is ever getting run. Thanks.

--EDIT 2-- When I call console.log(data) in my index file I see 'parsererror' in the console. Does anyone know what might cause this?

To me, it looks like your not sending your post data through correctly in your AJAX request. You shouldn't be wrapping it in quotes it should look like this:

data: {
   "body" : "value",
   "to" : "value",
}

Make sure you check your post data is coming through on your PHP side too.

Also you can parse JS in PHP. (Your mail.php file)

console.log is a javascript function. You are parsing PHP in that part- you're trying to use javascript in php, which is fundamentally an impossible thing.

Ajax works by sending a request of data, and receiving a response back. It's the same thing you do when you visit a web page: you request a page, and you get HTML back. With AJAX, you request a resource, and you get JSON back (thus the name AJAX: Asynchronous Javascript and XML). The stuff between the PHP tags is the server working by itself, independent of the client. You need to understand the difference here before you continue.

Secondly, remove your <script> tags from your PHP script and it'll probably just solve your problem. Otherwise, you're supplying incorrect arguments to the mail() function.

--Edit--

Also, you are formatting your "data" parameter for your request wrong. Code it as an actual JSON variable: Yours:

data: "{ 'body':'"  + latestResult + "'," +
                     "'to': '" + email + "'," +
                     "'subject': " + subject + "'" +
                 "}",

Mine:

data: {body:latestResult,
       to:email,
       subject:subject
       },

Read up on JSON (Javascript Object Notation) if you are confused about the difference between yours and mine.

Hope this helps!

You've got several problems caused by trying to mix javascript and php, and there's some confusion about what's actually being returned by the ajax request (json? html?)

This version might work a bit better:

var myUrl = "http://mywebsite/mail.php";
console.log(email);
$.post(myUrl, {body: latestResult, to: email, subject: subject}, function(data) {
    console.log(data.subject);
    console.log(data.to);
    console.log(data.body);
    alert('Worked')
}, 'json');

With a PHP file that looks like this:

<?php
$subject = $_POST['subject'];
$to = $_POST['to'];
$body = $_POST['body'];
$header = "From:someone@something.com 

           Content-type: text/html
";

//Send the email.
mail($to, $subject, $body, $header);
echo(json_encode(array('subject' => $subject, 'to' => $to, 'body' => $body)));
?>

Basically, all the console.log() stuff is now happening in javascript-land where it belongs. The PHP script is sending the email, and then returning a JSON document with the subject, to, and body values... which can then be logged by the javascript function that's run on completion.

change index.html to:

var myUrl = "http://mywebsite/mail.php";
    console.log(email);
    $.ajax({
       type: "POST",
       url: myUrl,
       cache: false,
       contentType: "application/json; charset=utf-8",
       data: "{ 'body':'"  + latestResult + "'," +
                 "'to': '" + email + "'," +
                 "'subject': " + subject + "'" +
             "}",
       dataType: "json",
       complete: function(transport, data){
                   console.log(data);

                    if (transport.status == 200) 
                        alert("Worked.");
                    else 
                        alert("Didn't work, " + transport.status); 
                }
   });

Notice the console.log(data) line, this will log whatever the mail.php page displays. Note this will not show your console.log messages. So now change your mail.php to this:

    <?php

$subject = $_POST['subject'];
$to = $_POST['to'];
$body = $_POST['body'];
$header = "From:someone@something.com 

            Content-type: text/html
";

echo $subject;
echo $to;
echo $body;
echo $header;

?>

This should give you the info you need to troubleshoot further.

EDIT to return JSON formatted data:

    <?php

$subject = $_POST['subject'];
$to = $_POST['to'];
$body = $_POST['body'];
$header = "From:someone@something.com 

            Content-type: text/html
";

$array = array(
    "subject" => $subject,
    "to" => $to,
    "body" => $body,
    "header" => $header,
);

echo json_encode($array);


?>

Take this one step at a time.

First, make sure your PHP file is properly sending email. Do this by creating a simple form to post to it like this:

<form method=post action="http://mywebsite/mail.php">
    <input type=text name=subject value="Sample Subject" />
    <input type=text name=to value="me@myemail.com" />
    <input type=text name=body value="Sample Body" />
    <input type=submit value="Send Mail" />
</form>

Now, you can just echo() from your PHP file, and whatever you echo will be displayed in the browser.

Once you have the PHP file working properly, you can start posting to it with ajax. You should define a data variable like this:

var postData = {
    body: latestResult,
    to: email,
    subject: subject        
}

...and then log the entire array to the console with console.log(postData).