Laravel表单选择onChange值通过AJAX保存到数据库

时间:2018-06-05 05:44:33

标签: javascript php jquery ajax laravel

我有一个由控制器(FocalController.php)中的以下代码生成的下拉列表:

  $focalData = DB::table('role_users')->orderBy('users.id','DESC')
            ->leftJoin('users', function($join){
                $join->on('role_users.user_id', '=', 'users.id');
                $join->on('role_users.role_id', '=', DB::raw("'1'"));
            })
            ->select('users.id',DB::raw('CONCAT(users.name) AS focal'))
            ->groupBy('users.id')
        ->get();

    foreach($focalData as $data):
        $focals[$data->id] = $data->focal;
    endforeach;

在视图中,我有以下块生成下拉列表:

{!! Form::select('focal', [''=>'select focal']+ collect($focals)->toArray() , $project_focal, array('class' => 'form-control','onchange'=>'changeFocal(this, '.$project->id.')' ))!!}

enter image description here

我想提交下拉值onChange并使用AJAX保存该值。

我提交表单的ajax如下:

    function changeFocal(e,project_id) {

        var focal_id = $("#e").val();
        var project_id = $("#project_id").val();

        $.ajax({
            type: "PUT",
            data: "focal_id=" + e + "&project_id=" + project_id,
            url:  "{{ URL::to('admin/focal') }}",
            success:function(data){
                console.log(data);$("#msg").html("New Focal Assigned.");
            }
        });
    }

我的路线是:

Route::post('admin/focal/','FocalController@saveFocal');

我的saveFocal中的FocalController函数是:

public function saveFocal(Request $request){
        $focal_id = $request->focal_id;
        $project_id = $request->project_id;    
        $project = Project::find('idea_id', $project_id)
                    ->update([
                        'focal' => $focal_id,
                        'updated_at' => \Carbon\Carbon::now()->toDateTimeString(),
                    ]);
        @\App\Common::createAccessLog($project->focal, "Update Project Focal for Project#" . $project->idea_id . "(" . $project->name . ")");
        return view('admin/focal');
    }

我在控制台中收到以下错误: enter image description here

任何人都可以告诉我我做错了什么,如何使用ajax和成功消息将选择数据保存到数据库。

2 个答案:

答案 0 :(得分:0)

使用POST代替PUT

还要确保您发送请求的路线有效且存在

以下几点更正:

function changeFocal(e,project_id) {

    var focal_id = $(e).val(); //correction
    var project_id = $("#project_id").val();

    $.ajax({
        type: "PUT",
        data: "focal_id=" + focal_id + "&project_id=" + project_id, //correction
        url:  "{{ URL::to('admin/focal') }}",
        success:function(data){
            console.log(data);$("#msg").html("New Focal Assigned.");
        }
    });
}

答案 1 :(得分:0)

Ude where请改为find

  Project::where(

find适用于主键