PHP从Ajax调用接收空的$ _POST变量 [英] PHP receives empty $_POST variables from Ajax call

查看:230
本文介绍了PHP从Ajax调用接收空的$ _POST变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AJAX调用将表单数据发送到PHP脚本.我正在对表单数据进行序列化,并通过POST方法将其作为JSON变量发送到PHP脚本. Ajax数据变量似乎是正确的,但是由于某些原因,PHP $ _POST数组为空,因此我很难理解我在这里做错了什么.

I am trying to send form data to a PHP script by using an AJAX call. I'm serializing the form data and sending it as a JSON variable, by a POST method, to a PHP script. Ajax data variable seems correct, but for some reason the PHP $_POST array is empty and I'm having a hard time understanding what I am doing wrong here.

这是我的ajax电话

// AJAX
        var input_data = $('#contact-form').serialize(); 

        event.preventDefault();

        $.ajax({
            url: 'contact.php',
            type:'POST',
            dataType:'json',//return type from server side function [return it as JSON object]
            contentType: "application/json",
            data: input_data, //Pass the data to the function on server side
            success: function (data) { //Array of data returned from server side function

                $.each(data,function(index){
                    alert(data[index]); // used for debugging, returns 1
                });
            }

        });

        alert("called");
        if(input_data.length < 1)
        {
            alert("empty");
            alert(input_data);
        }
        else
        {
            alert("not empty");
            alert(input_data);
        }
        return false; 

表格

<form class="text-center" id="contact-form" method="POST" action="contact.php">
                    <div class="form-group">
                        <input type="text" class="form-control" id="name" name="name" placeholder="Name">
                    </div>
                    <div class="form-group">
                        <input type="email" class="form-control" id="email" name="email" placeholder="Email">
                    </div>
                    <div class="form-group">
                        <textarea class="form-control" rows="5" id="msg" name="msg" placeholder="Type your message"></textarea>
                    </div>
                    <div class="form-group">
                        <div class="g-recaptcha buffer" data-sitekey="some_key" data-callback="recaptcha_callback"></div>
                        <input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
                    </div>


                    <button type="submit" class="btn btn-lg btn-primary text-uppercase buffer">Send message</button>
                </form>

最后是我的contact.php脚本

And finally my contact.php script

<?php
    header('Content-Type: application/json');

    $name;
    $email;
    $msg;

    $nameErr = $emailErr = $msgErr = 0;

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["name"])) {
            $nameErr = 1;
        }
        else {
            $name = $_POST["name"];
            $nameErr = 0;
        }

        if (empty($_POST["email"])) {
            $emailErr = 1;
        }
        else {
            $email = $_POST["email"];
            if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
                $emailErr = 0;
            } else {
                $emailErr = 1;
            }
        }

        if (empty($_POST["msg"]))  {
            $msgErr = 1;
        }
        else {
            $msg = $_POST["msg"];
            $msgErr = 0;
        }

        if($nameErr == 0 && $emailErr == 0 && $msgErr == 0)
        {
            $to = "example@example.com";
            $subject = 'Contact request - site';
            $txt = $_POST['msg'];
            $headers = "From: " . $_POST['email'] . "\r\n";
            mail($to,$subject,$txt,$headers);
            echo json_encode(array("sent"));
        }
        else
        {
            echo json_encode(array($nameErr, $emailErr, $msgErr));
        }
    }
    else
    {
        echo json_encode(array("post_error"));
    }

?>

通过运行PHP代码,可以正确发送电子邮件.使用Ajax调用时,$ _POST数组为空,并且从PHP代码中的最后一个if语句发送回三个错误代码.另外,如果有更好的方法可以完成此任务,那么我很乐意看到替代方案.感谢您的帮助.

By running PHP code, the email gets send correctly. When using an Ajax call, $_POST array is empty and it sends back three error codes from the last if statement in PHP code. Also, if there is a better way to acomplish this, I would be more than happy to see an alternative. I appreciate any help, thank you.

JSON数据

推荐答案

使用$('#contact-form').serialize(),您可以使jQuery将常规字段中的数据转换为HTTP查询字符串key=val&key2=val2&...-但现在您在$.ajax中进行了设置contentTypeapplication/json,这使jQuery为请求设置HTTP标头Content-Type: application/json. jQuery不会抱怨它可能是错误的Content-Type-您应该最了解它.

By using $('#contact-form').serialize() you make jQuery convert the data from regular fields to a HTTP query string key=val&key2=val2&... - but now you set in $.ajax that the contentType is application/json, which makes jQuery set a HTTP header Content-Type: application/json to the request. jQuery will not complain that it might be the wrong Content-Type - you should know it the best.

由于POST请求的内容类型为application/json,因此PHP不会将HTTP POST数据解析为超全局$_POST.相反,您必须从php://input读取原始POST数据.

Since the POST-Request has the Content-Type application/json, PHP will not parse the HTTP POST data into the superglobal $_POST. Instead you have to read the raw POST data from php://input.

现在的问题是,您告诉HTTP POST数据是JSON,但实际上不是发送的JSON,而是HTTP查询字符串.由于它是HTTP查询字符串,因此您可以从$.ajax调用中删除contentType: "application/json",,这将使jQuery设置正确的Content-Type标头.

Your problem is now, that you tell the HTTP POST data is JSON, but it's really not JSON what you send - it's a HTTP query string. Since it's a HTTP query string, you can remove contentType: "application/json", from your $.ajax call, which will make jQuery set the correct Content-Type header.

jQuery会将Content-Type标头设置为application/x-www-form-urlencoded-这是适合您的正确Content-Type标头.由于这是Content-Type PHP解析的内容之一,因此HTTP POST数据现在在超全局$_POST中可用.

jQuery will set the Content-Type header to application/x-www-form-urlencoded - which is the correct Content-Type header for you. Since that is one of the Content-Type PHP parses, the HTTP POST data is now available in the superglobal $_POST.

$_POST将仅在特定的Content-Type(即multipart/form-dataapplication/x-www-form-urlencoded)上填充.如果HTTP Content-Type都不是,则不会填充$_POST,您必须从php://input读取RAW POST数据.

$_POST will only be filled on specific Content-Types, namely multipart/form-data and application/x-www-form-urlencoded. If the HTTP Content-Type is neither of them, $_POST will not be filled and you have to read the RAW POST data from php://input.

http://php.net/manual/en/reserved.variables .post.php

这篇关于PHP从Ajax调用接收空的$ _POST变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆