Laravel Ajax没有从表单获取值到Controller

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Laravel Ajax没有从表单获取值到Controller相关的知识,希望对你有一定的参考价值。

在Ajax代码中我有action = 'contact';,联系人在路由文件中使用:

Route::post('contact', array('uses' => 'FormsController@send', 'as' => 'post_form'));

在路由文件中我有FormsController@send它是文件php发送电子邮件:

$name = Input::get('name');

$getSubject = "Subject of my email";
$myEmail = 'myEmail@gmail.com';

$uid = md5(uniqid(time()));
$eol = "
";

// header
$header = "From: " . $name . " <" . $email . ">
";
$header .= "MIME-Version: 1.0" . $eol;
$header .= "Content-Type: multipart/mixed; boundary="" . $uid . """ . $eol;
$header .= "Content-Transfer-Encoding: 7bit" . $eol;
$header .= "This is a MIME encoded message." . $eol;

// message & attachment
$nmessage = "--" . $uid . "
";
$nmessage .= "Content-Type: text/plain; charset="iso-8859-1"" . $eol;
$nmessage .= "Content-Transfer-Encoding: 8bit" . $eol;
if($name != ''){$nmessage .= "Name: " . $name . "

";}


// $nmessage .= "Wiadomość:
" . $getMessage . "

";
$nmessage .= "--" . $uid . "
";
$nmessage .= "Content-Transfer-Encoding: base64
";
$nmessage .= "--" . $uid . "--";

$send = mail($myEmail, $getSubject, $nmessage, $header);

Ajax指向控制器文件并绕过表单,因此控制器文件不会从表单中下载任何数据,也无法发送邮件。我不知道如何将数据从表单传递到控制器文件。

我的Ajax:

    const sendForm = function () {
        action = 'contact';

        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open('post', action, true);                
        xmlhttp.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
                const getMessageSend = document.querySelector("#messageSend");
                getMessageSend.innerText = "Thank you for sending an email. You will receive an answer shortly.";
            } else {
                const getMessageSendError = document.querySelector("#messageSendError");
                getMessageSendError.innerText = "An error occurred and the email was not sent.";
            }
        };

        // xmlhttp.open("post", action, true);
        // xmlhttp.send();

        const token = document.querySelector('meta[name="csrf-token"]').content;

        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        xmlhttp.setRequestHeader('X-CSRF-TOKEN', token);
        xmlhttp.send();

    };

    const sendMail = function() {

        options.form.addEventListener('submit', function (e) {
            e.preventDefault();
            let validate = true;
            const elementsRequired = document.querySelectorAll(":scope [formHr]");

            [].forEach.call(elementsRequired, function(element) {
                const type = element.type.toUpperCase();

                if (type === 'TEXT') {
                    if (!validateText(element)) {validate = false;}
                }

            });
            if (validate) {
                sendForm();
                // this.submit();
            } else {
                return false;
            }

        });

    };

我的表格:

{!! Form::open(['action'=>['FormsController@send'], 'method' => 'post', 'class' => 'form', 'novalidate' => 'novalidate', 'files' => true]) !!}

 <input type="text" name="name" placeholder="Name"  formHr>

{!! Form::submit('Send', ['class' => 'submit-btn']); !!}
{!! Form::close() !!}
答案

我找到了解决方案。帮我这个主题Submit form laravel using AJAX

我只是将data添加到我的代码中:

$.ajax({
    type: "POST",
    url: 'contact',
    data: $(this).serialize(),
    success: function () {
        $("#messageSend").addClass("message-send");
        $("#messageSend").text("Thank you for sending an email. You will receive an answer shortly.");
    }
});

记得使用完整版Jquery!

以上是关于Laravel Ajax没有从表单获取值到Controller的主要内容,如果未能解决你的问题,请参考以下文章

laravel 8 没有从 ajax 请求中获取数据

如何使用 ajax (codeigniter) 在我的编辑表单中获取和显示选定值到 <select2> 标记中

如何从循环中获取值到刀片 - laravel

如何从数据库中获取图像并在 laravel 中使用 ajax 以编辑形式预览它?

如何从表单获取输入框值到iframe?

php 从db获取默认值到select表单