I'm having trouble with seemingly simple problem.
Using JQuery i want to POST an array containing 2 items, an email address and email content, to a simple PHP script that mails the customer's concern back to my own server email.
I am receiving the email, but it is blank because either im not encoding or decoding the JSON object correctly or something else.
Javascript:
...
var JSONEmailRequest = new Object();
JSONEmailRequest.emailaddress = $("#emailInput").val();
JSONEmailRequest.content = $("#contentInput").val();
$.post("/email.php", JSON.stringify(JSONEmailRequest), function (data) {
//do stuff
});
...
PHP:
<?php
$POSTJSONObj = json_decode($POST['JSONEmailRequest']);
$email_to = "shawnandrews@saportfolio.ca";
$email_subject = "User enquiry from ".$POSTJSONObj['emailaddress'];
$email_body = $POSTJSONOb j['content'];
$result = mail($email_to,$email_subject,$email_body,"From: ".$email_to);
if(!$result) {
echo false;
} else {
echo true;
}
?>
Don't convert the JSONEmailRequest
to JSON. $.post
expects the data argument to be either an object or a string in www-form-urlencoded format. So do:
$.post("/email.php", JSONEmailRequest, function(data) {
...
}, "json");
And in the PHP code, use $_POST
to get the parameters, and json_encode
to send the result back.
<?php
$email_to = "shawnandrews@saportfolio.ca";
$email_subject = "User enquiry from ".$_POST['emailaddress'];
$email_body = $_POST['content'];
$result = mail($email_to,$email_subject,$email_body,"From: ".$email_to);
echo json_encode($result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.