使用带有ajax调用的资源控制器的存储方法将数据插入到db

时间:2016-12-20 06:09:57

标签: javascript php ajax laravel

在我的laravel项目中,我通过资源控制器插入数据。但是现在我想使用具有相同路由的ajax请求和资源控制器的相同方法插入如何发送url以及如何将表单数据发送给它。

路线

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
//----models--------
use App\Make;
class Makecontroller extends Controller
{
    public function index()
    {
        return View("pagination_common.index");
    }

    public function create()
    {

    }
    public function store(Request $request)
    {
        $input['name'] = Input::get('name');
        $rules = array('name' => "unique:makes,name");
        $validator = Validator::make($input, $rules);
        if ($validator->fails()) { 
            return Redirect::back()->with('alert-danger',"Make Name already exist.")->withInput();
        }
        else{
            $make = new Make();
            $make_detail = $make->add_make($request);
            $data['name'] = $request->name;
            $make = make::find($make_detail['id']);
            activity('create')->performedOn($make)->log('');
            return redirect('/makes')->with('alert-success', 'Make Created successfully.');
        }
    }
    public function show($id)
    {

    }    
    public function edit($id)
    {

    }    
    public function update(Request $req, $id)
    {

    }
    public function destroy($id)
    {

    }
}

控制器

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\softDeletes;
use DB;
class Make extends Model
{
    use SoftDeletes;
    public function add_make($req)
    {
        $this->name = $req['name'];
        $this->save();
        return ['id' => $this->id];
    }
    public function edit_make($req,$id)
    {
        $make = $this->find($id);
        $make->name = $req->name;
        $make->save();
    }
    public function make_detail($id)
    {
        $client = DB::select('select * from makes WHERE id=:id',['id'=>$id]);
        return $client;
    }
}

模型

<div class="modal" id="add_item">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Add Make</h4>
            </div>
            {{ Form::open(array('class' => 'form-horizontal form-validate-jquery','id' => 'add_item_form')) }}
            {{ Form:: hidden('model', "make","" ) }}
            <div class="modal-body">
                <fieldset class="content-group">
                    <legend class="text-bold"></legend>
                        <div class="form-group">
                            <label class="control-label col-lg-3">Name: <span class="text-danger">*</span></label>
                            <div class="col-lg-9">{{ Form:: text('name', null, array('class' => 'form-control', 'required' => '','placeholder' => 'name', 'maxlength' => '50')) }}</div>
                        </div>
                </fieldset>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm btn-primary" id="item-add-btn" data-resource="faq" onclick="add_item_common('make','Make')" >Submit</button>
                <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Cancel</button>
            </div>
            {{ Form::close() }}
        </div>
    </div>
</div>

添加表单div

function add_item_common(model,item)
{
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    var objectResult = $('#add_item_form').serializeArray();
    $.ajax({
           type: "POST",
           url: "makes",
           dataType: 'json',
           data: {
               _token: CSRF_TOKEN,
               fields: objectResult
           },
           success: function (data) {
               console.log(data);
               if(data=='success')
               {
                   var page = $(".pagination .active span").html();
                   ajaxLoad('{{Request::segment(1)}}?page='+page);
                   $('#delete_confirm').modal('hide');
                    var add_success = '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert"><span>×</span><span class="sr-only">Close</span></button>'+model+' '+item+' added successfully.</div>';   
                    $(".content").prepend(add_success);
                    setTimeout(function(){ $(".alert-success").remove(); }, 5000);
               }
           }
    });  

}

ajax函数的js代码

{{1}}

2 个答案:

答案 0 :(得分:2)

删除dataType: 'json',并将data更改为data:$("#add_item_form").serialize()

应该这样做。

答案 1 :(得分:2)

用以下内容替换你的ajax代码。

 $.ajax({
          type: "POST",
          url: "makes",
          data:$("#add_item_form").serialize(),
          success: function (data) {
              console.log(data);
          }
   });