【问题标题】:How to serialize form in ajax and save data in database with laravel?如何在ajax中序列化表单并使用laravel将数据保存在数据库中?
【发布时间】:2021-07-13 11:22:46
【问题描述】:

我有一个表单,用户可以在其中插入多个输入字段并使用 ajax 保存到数据库 这是输入,

我正在尝试将序列化表单发送到我的数据库。我的问题是,当我序列化表单时,使用 JQuery 将其附加到隐藏的输入字段,然后将表单和一些其他信息发送到数据库,其余信息到达数据库但我仍然有一个空白序列化形式在哪里。如果有人能指出我哪里出错和/或解释应该如何做,我将不胜感激!非常感谢!

刀片

<form method="post" id="form-job-store">
    <input type="hidden" name="url" value="{{ route('job.store') }}">
    @csrf
    <div class="row">
        <div class="col-md-6 mb-3">
            <div class="col-md-6 mb-3">
                <label for="history">history</label>
                <input type="text" class="form-control" id="history" name="history">
            </div>
            <div class="col-md-6 mb-3">
                <label for="post_title">post_title</label>
                <input type="text" class="form-control" id="post_title" name="post_title">
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6 mb-3">
            <button type="submit" class="btn btn-success" id="btn-job-submit"><i class="fas fa-plus fa-xs"></i> Save</button>
        </div>
    </div>
<form>

脚本

$(document).ready(function () {
    $('#btn-job-submit').on('click', function (event) {
        event.preventDefault();
        var formData = new FormData($('#form-job-store')[0]);
        let url = $('#form-job-store :input')[0].getAttribute('value');
        $.ajax({
            type: 'POST',
            url,
            data:  $(formData).serialize(),
            success: function (data) {
                alert(data);
            },
        });
    });
});

web.php

Route::resource('job', 'JobController');

JobController.php

public function store(Request $request)
{
    $job = Job::create([
        'user_id' => auth()->id(),
        'post_title' => $request->post_title,
        'history' => $request->history,
    ]);
    return response()->json($job);
}

【问题讨论】:

  • 你不需要序列化它,formdata(查一下)已经做到了
  • 所以试试data: formData,
  • 此代码在表(数据库)中创建一个新行。但它没有填写信息。
  • 调试:Step1:: 你试过dd($request); 看看$request 里有什么

标签: php jquery ajax laravel


【解决方案1】:

你必须这样使用

$(document).ready(function(){
    $('#btn-job-submit').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url:'{{route('job.store')}}',
            method:"POST",
            data:new FormData(this),
            dataType:'JSON',
            contentType: false,
            cache: false,
            processData: false,
            success:function(data){

            }
       })
   })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多