【问题标题】:Laravel Ajax update request is duplicating dataLaravel Ajax 更新请求正在复制数据
【发布时间】:2019-09-28 12:35:20
【问题描述】:

我正在尝试使用 ajax 更新数据,但我的数据被复制了, 由于ajax URL,我不确定我是否正确传递/

Ajax 代码:

jQuery(document).ready(function($)  {
$('#update-form').on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",      

 url: "teachers/" + $('#update-id').attr("value"), //error is here

            dataType: 'json',
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
            data : $(this).serialize(),

            success: function (data) {

                alert("updated");
            },
        });
    });
});

查看代码:

我有一个包含教师列表的表格,以及每个教师的编辑按钮;

<button type="button" id="btn" value="{{ $teacher->id }}" class="btn btn-primary btn-block btn-sm edit-btn">Edit</button>

在表单中我有隐藏字段

<form method="post" id="update-form">
        {{ method_field('PATCH') }}
        <input type="hidden" id="update-id" value="{{$teacher->id}}" >

            <div class="">
                <label for="efirst">efirst</label>
                <input type="text" class="form-control" name="efirst" id="update-efirst">
                <textarea name="esecond" class="form-control" id="update-esecond" rows="6"></textarea>
            </div>

                <button type="submit" class="btn btn-success"  id="update-submit">Update</button>
        </form>

当我点击更新时,教师 ID 正在更改,一个教师 ID 变为另一个教师 ID。从隐藏字段传递教师 ID 是否正确?

【问题讨论】:

  • 显示您的表单 html 代码
  • @RiponUddin 请检查添加的表单
  • 点击编辑按钮会发生什么?
  • 它以表格形式显示数据,每个老师在编辑按钮上都有不同的数据。这工作正常
  • @iMatti 在表单标签开始后添加 {{ csrf_field() }}

标签: ajax laravel


【解决方案1】:

像下面这样写路线名称

在 Web.php 中

Route::post("teacher/{id}/edit","YourController")->name("teacher.update");

在刀片文件中

$('#update-form').on('submit', function (e) {
    e.preventDefault();
    var id = $('#update-id').val(); // $('#update-id').attr("value") also ok
    $.ajax({
        method: "post",  
        url: "{{ route('teacher.update',id) }}",
        dataType: 'json',
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
        data : $(this).serialize(),
        success: function (data) {
            alert("updated");
        },
    });
});

试试这个。 会成功的

【讨论】:

  • 如果我对 1 进行分页以显示表中的一条记录,则 id 1 记录正在更新,如果我显示 2 条记录,那么如果我更新 id 1,则 id 2 正在更新。跨度>
  • 且无需声明表单内的任何隐藏字段并更改 url:$(this).attr("action"),
  • app.js:10216 POST isp.local/teachers/%20http://isp.local/teachers/208 404(未找到)
猜你喜欢
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 2018-03-15
  • 2015-02-11
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
  • 2020-03-03
相关资源
最近更新 更多