如何在Laravel上使用Ajax表单插入

时间:2018-07-19 15:05:55

标签: ajax laravel

路线: 这是我的路线

Route::get('admin/category', 'CategoryController@category')->name('category');
Route::post('admin/category_add', 'CategoryController@add_category')- 
 >name('add_category');

我的控制器: 这是我的控制器功能

  public function add_category(Request $request){
        $name = $request->input('name');
        $city = $request->input('status');
        DB::table('categorys')->insert(['name' => $name, 'status' => $city]);
        return redirect()->back()->with('message', 'SuccessFully Insert');
   }

表格:

      <form  id="category">
            <input type="name" name="name" class="form-control" id="name">
            <input type="radio" value="1" id="status" name="status">
            <input type="radio" value="2" id="status" name="status">
            <input type="submit" value="Subscribe" name="subscribe" 
            id="submit">
           <input type = "hidden" id="token" name = "_token" value = "<?php echo csrf_token(); ?>">
     </form>

Jquery Ajax:这是我的jquery ajax函数如何插入数据库

$("#submit").click(function(event) {
  $.ajax({
   var name = $("input#name").val();
   var status = $("input#status").val();
   data: {name: name,status:status,"_token": "{{ csrf_token() }}"},
        type: "post",
        dataType: 'json',
        url: "{{url('admin/category_add')}}",
        },
        success: function(data){}
        }); 
  });

1 个答案:

答案 0 :(得分:0)

正确的add_category

public function add_category(Request $request){
    $category = new App\Category();
    $category->name = $request->input('name');
    $category->status = $request->input('status');
    $category->save();
    return response()->json('ok');
 }