简体   繁体   中英

PHP Post Values undefined

when i am trying to get my POST values from my php class, it always return "Undefined variable"

But how it can be undefined i really did not getting it!!!

This is my POST data

在此处输入图片说明

This is my Response data

在此处输入图片说明

This is my PHP code --

class sendMailController extends Controller {

        protected function init() {
        $this->saveDataAction();
    }

    public function saveDataAction() {
        if($_SERVER["REQUEST_METHOD"]=='POST'){
            $_POST['name'] = $name;
            $_POST['email'] = $email;
            $_POST['message'] = $msg;
            print_r($name);
        }
    }
}

this is my script ---

<script>
    $(document).ready(function () {
        $("#myForm").on('submit', function (e) {
            var data = {};
            data['name'] = $("#name").val();
            data['email'] = $("#email").val();
            data['message'] = $("#message").val();

            $.ajax({
                url: '/mvc/sendmail',
                type: 'post',
                data: data,
                success: function (returnedData) {

                }
            });
            return false;
        });
    });
</script>

Do any one knows where i am making the mistake !!! Please really need some advice

You are doing reverse assignment, Here is correct

class sendMailController extends Controller {

        protected function init() {
        $this->saveDataAction();
    }

    public function saveDataAction() {
        if($_SERVER["REQUEST_METHOD"]=='POST'){
            $name = $_POST['name'] ;
            $email = $_POST['email'] ;
            $msg = $_POST['message'] ;
            print_r($name);
        }
    }
}

This is wrong: $_POST['name'] = $name . You assign the value of the undefined variable $name to the post element $_POST['name'] . Assignments are always right value into left variable, in all programming languages. You need to reverse it like: $name = $_POST['name'] ;

I believe instead of using "$_POST" try to use like so ---

class sendMailController extends Controller {

        protected function init() {
        $this->saveDataAction();
    }

    public function saveDataAction() {
        $request = $this->getRequest();

           if ($request->getMethod() == 'POST') {

            $name = $request->request->get('name');
            $email = $request->request->get('email');
            $message = $request->request->get('message');
        }
    }
}

I believe this is a better practise for getting the POST values

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM