javascript - 从没有页面刷新的模式异步 Ajax 保存 Laravel 5.2

标签 javascript php ajax laravel laravel-5

使用 Laravel 5.2.45

我有一个数据库,其中包含一些表格,例如“用户”、“类别”和“联系人”。

用户可以创建一个联系人并为其分配一些类别。

联系人表中,我有这个架构:

public function up()
    {
        Schema::create('contacts', function (Blueprint $table) 
        {
            $table->engine = 'InnoDB';

            $table->integer('id')->unsigned()->autoIncrement();
            $table->integer('user_id')->unsigned();            
            $table->string('image');
            $table->string('name');
            $table->string('lastname');
            $table->string('email', 191);
            $table->string('phone',191);
            $table->string('address');
            $table->string('description', 255);
            $table->integer('category_id')->unsigned()->nullable();

        });

        Schema::table('contacts', function (Blueprint $table)
        {
            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('category_id')->references('id')->on('categories');

        });
    }

请注意,有一列用于获取您为联系人选择的类别的 ID。

这是 categories 表的架构:

public function up()
    {
        Schema::create('categories', function (Blueprint $table) 
        {
            $table->engine = 'InnoDB';

            $table->integer('id')->unsigned()->autoIncrement();
            $table->string('category')->required()->unique()->index();
        });
    }

要在联系人表中输入属性,我在 ContactsController Controller 中有以下内容:

public function create(CreateContactRequest $request)
    {
        $contact                = new Contact;            
        $contact-> name         = $request->get('name');
        $contact-> lastname     = $request->get('lastname');
        $contact-> email        = $request->get('email');
        $contact-> phone        = $request->get('phone');
        $contact-> address      = $request->get('address');
        $contact-> description  = $request->get('description');
        $contact-> user_id      = \Auth::user()->id;
        $contact-> category_id  = $request->get('category');
        // $contact-> category     = $request->get('category');

        // Checking if input has a file
        if ($request->hasFile('image')) 
        {            
            // It does, so set name to a random string with 10 chars
            $fileName = str_random(10);

            // Get the extension of the file (.jpg, .png...)
            $fileName .= '.' . $request->file('image')->getClientOriginalExtension();

            // Move the file to the storage
            $request->file('image')->move(storage_path('app/public/uploads'), $fileName);

            $contact->image = $fileName;
        }

        $contact->save();

        $contacts = App\Contact::where('user_id', \Auth::user()->id)->get();
        return redirect(route('contacts', compact('contacts')));
    }

最后,您将被重定向到 contacts View ,您只会在其中看到包含所有列的 contacts 表。

输入联系人的表单是这样的:

Contact Form
**Basically, inputs for the columns name, lastname, email, phone, address and description.** 

<div class="row">
    <div class="col-lg-10 col-lg-offset-1">
        <div class="panel">
            <div class="panel-heading">
                <h2 class="panel-title"> Contact Form </h2>
            </div>
            {!! Form::open(['route' => ['contacts.create'], 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
                <div class="panel-body">
                    <div class="row">
                        <div class="col-md-4 col-md-offset-1">
                            <div class="form-group">
                                {!! Form::label('category', 'Choose Your Contact Category') !!}
                                <fieldset>
                                    <select name="category" class="form-control" id="category">
                                        <option disabled="true" selected="true">
                                            List
                                        </option>                            
                                        @foreach ($categories as $category)
                                            <option name="category" id="category" class="category" value="{!! $category->id !!}">
                                                {!! $category->category !!}
                                            </option>
                                        @endforeach
                                    </select>
                                </fieldset>
                            </div>
                        </div>
                        <div class="col-md-4 col-md-offset-1">
                            <label>
                                Create Your Contact Category
                            </label><br/>
                            <button type="button" data-toggle="modal" data-target="#demo-default-modal">
                                <i class="fa fa-plus"></i> Create New Category
                            </button>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class = "form-group
                                @if($errors->has('name'))
                                    has-error
                                @endif"> 
                                {!! Form::label('name', 'Name *') !!}
                                {!! Form::text('name', old('name'),['class'=>'form-control', 'placeholder' => 'Name of your contact']) !!}
                                @if($errors->has('name')) 
                                    <p class = "help-block"><span class="label label-danger">Warning</span> {{ $errors->first('name') }}</p>
                                @endif
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class = "form-group 
                                @if($errors->has('lastname'))
                                    has-error
                                @endif"> 
                                {!! Form::label('lastname', 'Lastname') !!}
                                {!! Form::text('lastname', old('lastname'),['class'=>'form-control', 'placeholder' => 'Lastname of your contact']) !!}                
                                @if($errors->has('lastname'))
                                    <p class = "help-block"><span class="label label-danger">Warning</span> {{ $errors->first('lastname') }}</p>
                                @endif
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class = "form-group 
                                @if($errors->has('email'))
                                    has-error
                                @endif">
                                {!! Form::label('email', 'E-Mail *') !!}
                                {!! Form::text('email', null,['class'=>'form-control', 'placeholder' => 'If your contact does not have one use contactName@email.com']) !!}
                                @if($errors->has('email'))
                                    <p class = "help-block"><span class="label label-danger">Warning</span> {{ $errors->first('email') }}</p>
                                @endif
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class = "form-group
                                @if($errors->has('phone'))
                                    has-error
                                @endif">
                                {!! Form::label('phone', 'Phone Number *') !!}
                                {!! Form::text('phone', null,['class'=>'form-control', 'placeholder' => 'If your contact does not have one, just insert three numbers at random']) !!}
                                @if($errors->has('phone'))
                                    <p class="help-block"><span class="label label-danger">Warning</span> {{ $errors->first('phone') }}</p>
                                @endif
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class = "form-group">
                                {!! Form::label('address', 'Address') !!}
                                {!! Form::text('address', old('address'),['class'=>'form-control', 'placeholder' => 'Street name, number, neighborhood, city, state initials, country']) !!}
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class = "form-group">
                                {!! Form::label('description', 'Description') !!}
                                {!! Form::text('description', old('description'),['class'=>'form-control', 'placeholder' => 'Something to describe your contact. Use a simple word, like family, work, friend and such']) !!}
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class = "form-group">
                                {!! Form::label('image', 'Upload an image!') !!}
                                {!! Form::file('image')!!}
                            </div>
                        </div>
                    </div>                
                    <div class="row">
                        <div class="col-md-3 col-md-offset-1">
                            <p class="text-left">
                                <strong> * = Required field (Can't be blank) </strong>
                            </p>
                        </div>
                    </div>
                </div>
                <div class="panel-footer text-right">
                    <div class = "btn">
                        {!! Form::button(' Submit Information', ['type' => 'submit', 'class' => 'btn btn-primary fa fa-plus-circle']) !!}
                    </div>
                </div>
            {!! Form::close() !!}
        </div>
    </div>
</div>

请注意,类别是从下拉列表 select 标记中插入的,其中选项是使用 option 标记渗透的。

如果您需要为您的联系人创建一个新类别,请按 Create Category 按钮,这将加载一个带有表单的模态以创建您的类别。

**Modal for category**

<div class="modal fade demo-default-modal" name="demo-default-modal" id="demo-default-modal" role="dialog" tabindex="-1" aria-labelledby="demo-default-modal" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button data-dismiss="modal" class="close" type="button">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h3 class="modal-title">
                    Create Category
                </h3>
            </div>

            {!! Form::open(['route'=>['category.create'], 'method'=>'POST', 'class'=>'modalForm', 'id'=>'modalForm', 'name'=>'modalForm']) !!}
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 col-md-offset-3">
                            <div class="form-group">
                                {!! Form::label('category', 'Category') !!}
                                {!! Form::text('category', NULL, ['placeholder'=>'Category Name', 'class'=>'form-control']) !!}
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    {!! Form::button('Close', ['type' => 'button', 'class' => 'btn btn-default', 'data-dismiss'=>'modal']) !!}
                    {!! Form::submit('Save Category', ['type' => 'submit', 'class' => 'btn btn-primary modalSave', 'name' => 'modalSave', 'id' => 'modalSave']) !!}
                </div>
            {!! Form::close() !!}
        </div>
    </div>
</div>

当您插入类别名称并单击 Save Category 按钮时,表单将通过路由设置为:

Route::post('category/create', [
    'as'=>'category.create', 'uses'=>'CategoryController@create', 'redirects'=>'phonebook', 'with'=>'input'
]);

路由在CategoryController的方法create中调用参数,即:

public function create(CreateCategoryRequest $request)
    {
        $category           = new Category;
        $category->category = $request->get('category');

        $category->save();

        return redirect('phonebook');
    }

目前一切正常,没有出现错误。

联系人被插入到正确的表格中,输入正确,即使类别 ID 也是在 categories 表格中创建的,也没有任何问题。

但问题是,我想从模式创建类别,但不刷新页面,因为让我们假设用户正在创建联系人,渗透所有输入字段并让类别最后选择。

想象一下这个用户必须为他的联系人创建类别。他将弹出模式,输入一些内容并单击发送按钮,这会将他重定向到表单,但没有他的所有输入。

请注意,在创建类别的路径中,我尝试传递参数以保留输入,但没有成功。

可能很重要

我的 View 是使用 Laravel 提供的 @include 语法设置的,所以它看起来像这样

插入联系人 View

phonebook.blade.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">

        <script src="/js/jquery-2.2.1.min.js"></script>
        <script src="/js/modalSaver.js"></script>
        <script src="/js/laroute.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <script src="js/nifty.min.js"></script>
        <script src="js/bootbox.min.js"></script>
        <script src="js/ui-modals.js"></script>

        <link href="{{URL::asset('docs/nifty-v2.4/demo/css/bootstrap.min.css')}}" rel="stylesheet">
        <link href="{{URL::asset('docs/nifty-v2.4/demo/css/nifty.min.css')}}" rel="stylesheet">
        <link href="{{URL::asset('docs/nifty-v2.4/demo/plugins/font-awesome/css/font-awesome.min.css')}}" rel="stylesheet">
        <link rel="stylesheet" href="{{URL::asset('css/infost.css')}}">
        <link rel="stylesheet" href="{{URL::asset('css/header.css')}}">

        <title> 
            Phonebook - Add a new contact
        </title>
    </head>

    <body>        
        @include('partials.header')

        @if(Auth::check())
            <br/><br/>
            @include('partials.contactForm')
        @else
            @include('partials.info')
        @endif
    </body>
</html>

partials.contactForm 部分是输入联系信息的表单和模态位所在的位置。

所以我尝试了 AJAX,但作为新手,我无法完成某些工作。

另外,请注意我在缩小文件中有 jquery-2.2.1

这些是我的尝试,顺便说一句,它们在 View 中的单独 .js 文件 (modalSaver.js) 中:

**function 1**

var $form = $("#demo-default-modal");

$form.submit(function(e)
{
    $.ajax({
        method: 'POST',
        url: 'category.create',
        data: $form.serialize(),
    });
    e.preventDefault();
});




**function 2**

var form = 'demo-default-modal';

$("form").submit(function(e)
{
    e.preventDefault()
    {
        $.ajax({
            method: 'POST',
            url: 'category.create',
            data: $form.serialize(),
        });
    }
});



**function 3**

$('form.modalForm').submit(function(event)
{
    event.preventDefault();
    $.post($(this).attr("action"),
    $(this).serialize(),
    function(info)
    {
        $("#result").html(info);
    });
});

如前所述,这些功能似乎都不起作用。

这是我的问题,最后(很抱歉发了这么长的帖子,但我尽量做到非常细致):

如何制作一个 AJAX 函数来保存我的数据库中的类别,在 categories 表中,显示我刚刚插入的类别列在下拉 select 标记列表中,位于表单中,并在不刷新页面的情况下执行所有这些操作,而只是简单地隐藏模式?

提前致谢。

最佳答案

将创建类别 Controller 更改为 return $category 而不是 return redirect。

比将您的 ajax 脚本更改为此

$('#modalForm').submit(function(e) {
  e.preventDefault();
  var $form = $(this);

  // get url from action attribute
  var $url = $(this).attr('action');

  $.ajax({
      method: 'POST',
      url: $url,
      data: $form.serialize(),
    })
    .done(function(res) {
      // make new option based on ajax response
      var option = '<option class="category" value="' + res.id + '">' + res.category + '</option>';

      // append option to catogory select
      $('#category').append(option);
    });
})

关于javascript - 从没有页面刷新的模式异步 Ajax 保存 Laravel 5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45194965/

相关文章:

javascript - jQuery getJSON 响应

javascript - 一切正常,但脚本中有 LAG?

javascript - 从当前月份向后返回数组

javascript - d3.js 在 Meteor 中未定义

javascript - jQuery ajax php 不返回任何内容

php - 使用 PHP 和 AJAX 对查询结果进行分页

javascript - 完成后获取 jQuery AJAX 请求的参数

javascript - getElementById 类型错误 : "cannot set property ' innerHTML' of null

javascript - 混淆了箭头函数javascript

javascript - Jquery + 追加 + PHP