我的PHP代码没有收到JSON数据

时间:2016-12-14 20:33:08

标签: javascript php jquery json

我有一个html表单,它使用jquery脚本来获取数据并推送到php文件以通过电子邮件发送给我。

jQuery:

'use strict';
var isValidElement = function isValidElement(element) {
    return element.name && element.value;
};
var isValidValue = function isValidValue(element) {
    return ![
        'checkbox',
        'radio'
    ].includes(element.type) || element.checked;
};
var isCheckbox = function isCheckbox(element) {
    return element.type === 'checkbox';
};
var isMultiSelect = function isMultiSelect(element) {
    return element.options && element.multiple;
};
var getSelectValues = function getSelectValues(options) {
    return [].reduce.call(options, function (values, option) {
        return option.selected ? values.concat(option.value) : values;
    }, []);
};

var formToJSON = function formToJSON(elements) {
    return [].reduce.call(elements, function (data, element) {
        if (isValidElement(element) && isValidValue(element)) {
            if (isCheckbox(element)) {
                data[element.name] = (data[element.name] || []).concat(element.value);
            } else if (isMultiSelect(element)) {
                data[element.name] = getSelectValues(element);
            } else {
                data[element.name] = element.value;
            }
        }
        return data;
    }, {});
};
var handleFormSubmit = function handleFormSubmit(event) {
    event.preventDefault();
    var data = formToJSON(form.elements);
     var request;

    request = $.ajax({
        url: "/dev/afelipeor/php/email.php",
        type: "POST",
        data: JSON.stringify(data)
    });
    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(JSON.stringify(data))
        $('.card').addClass('hide').after(emailSent);
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );

        });
    };
    var form = $('#contact-form')[0];

form.addEventListener('submit', handleFormSubmit);

和php:

<?php

$_POST = json_decode(file_get_contents('php://input'), true);
    $data = $_POST['data'];
    $to = "myemail@afelipeor.com";
    $subject = "Contact Form";
    $message = $data;

    mail($to,$subject,$message,"This is an automated email from the contact form", "From: system@afelipeor.com\r\n");
?>

jQuery代码正常运行,并输出预期的。但是,每次收到电子邮件时,邮件部分都是空的。

我看着整个互联网和堆栈溢出,并尝试了我发现的一切,但我仍然无法解决它。

任何帮助都将不胜感激。

0 个答案:

没有答案