【问题标题】:OctoberCMS callback for successful DB action after AJAX requestAJAX 请求后成功的数据库操作的 OctoberCMS 回调
【发布时间】:2020-08-25 08:44:07
【问题描述】:

我通过 AJAX 从我的 Chrome 扩展程序向我的 OctoberCMS 控制器发送数据。 如何在我的 Chrome 扩展程序中识别数据库操作成功? 所以目标是我可以在数据库更新成功后在我的 AJAX 调用中使用done()。 我必须从我的控制器返回一些东西吗?

来自扩展的 Ajax

$.ajax({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    url: "/saveData",
    type: "POST",
    dataType: "JSON",
    data: { "data": data}
}).done(function((){//does nothing});

OctoberCMS 控制器

  function saveData(Request $request)
{
    $data = post('data');

    //do some actions with the data;
    
    DB::table('users')->where(['id' => Auth::getUser()->id])->update(['data' => $data]);
}

【问题讨论】:

标签: php ajax laravel octobercms


【解决方案1】:

您可以检查响应

从服务器端

function saveData(Request $request)
{
    $data = post('data');

    //do some actions with the data;
    
    DB::table('users')->where(['id' => Auth::getUser()->id])->update(['data' => $data]);

    // if all good return success
    return ['success' => true];
    // if something is not correct
    // return ['success' => false];
}

客户端

$.ajax({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    url: "/saveData",
    type: "POST",
    dataType: "JSON",
    data: { "data": data}
}).done(function((data){
    if(data.success == true) {
       // yes all good data is updated
    }
    else {
       // data is not updated some error handling 
    }
}).fail(function() { 
    // data is not updated some error handling 
    // failed in case server is not able to answer or error 
});

如有任何疑问,请发表评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    相关资源
    最近更新 更多