简体   繁体   中英

Insert data to db using store method of resource controller with ajax call

In my laravel project i am inserting data through the resource controller .but now I want to insertion using ajax request with same route and same method of resource controller how i have send the url and how to send the form data to it.

route

Route::resource('/makes', 'MakeController');

controller

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)
    {

    }
}

model

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;
    }
}

Add form div

<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>

js code of ajax function

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);
               }
           }
    });  

}

remove dataType: 'json', and change data to data:$("#add_item_form").serialize()

That should do it.

Replace your ajax code with following.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM