weixin_33674437 2018-04-19 08:04 采纳率: 0%
浏览 35

使用Laravel Form进行Ajax调用

Hello can someone please help me because I wanted to use ajax in my laravel form, when everytime I hit 'CREATE POST' button, the table contains all my posts will hide and then the form will show, and when clicking the submit button in the form the table will then show with its new data inserted below the table and the form will hide. I have a code but it is not working.

Controller Code:

public function store(Request $request)
{
    //validate the data
    $this->validate($request, array(
        'title'       => 'required|max:255',
        'slug'        => 'required|alpha_dash|min:5|max:255|unique:posts,slug',
        'category_id' => 'required|integer',
        'body'        => 'required',
        'featured_image' => 'image|nullable|max:1999'
    ));

    //store in the database
    $post = new Post;

    $post->title = $request->title;
    $post->slug  = $request->slug;
    $post->category_id = $request->category_id;
    $post->body  = Purifier::clean($request->body);

    //Save Our Image
    if ($request->hasFile('featured_image')) {
        $image = $request->file('featured_image');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('images/'. $filename);
        Image::make($image)->resize(800, 400)->save($location);

        $post->image = $filename;
    } 
    $post->save();
    return response()->json($post);


    // Session::flash('success', 'The blog post was succesfully saved!');

    // //redirect to another page
    // return redirect()->route('posts.show', $post->id);

}

Route:

Route::resource('/posts', 'PostController');
Route::post('/addpost', 'PostController@store');

Form Code:

        {!! Form::open(['id' => 'form-post', 'method' => 'POST', 'route' => 'posts.store', 'data-parsley-validate' => '', 'files' => true]) !!}

        {{ csrf_field() }}

            <div class="form-group">
                <label class="control-label" for="title">Title:</label>
                <input type="text" name="title" class="form-control" data-error="Please enter title." required />
                <div class="help-block with-errors"></div>
            </div>

            <div class="form-group">
                <label class="control-label" for="title">Slug:</label>
                <input type="text" name="slug" class="form-control" data-error="Please enter title." required />
                <div class="help-block with-errors"></div>
            </div>


            {{ Form::label('category_id', 'Category') }}
            <select id="add-category" class="form-control" name="category_id">
                    @foreach($categories as $category)
                        <option value='{{ $category->id }}'>{{ $category->name }}</option>
                    @endforeach 
            </select>

           {{ Form::label('featured_image', 'Upload Featured Image:', ['class' => 'form-spacing-top']) }}
           {{ Form::file('featured_image',["id" => 'add-image', "class" => 'form-control-file']) }}


          {{ Form::label('body', 'Post Body:') }}
          {{ Form::textarea('body', null, array('id' => 'add-body', 'class' => 'form-control')) }}

          {{ Form::button('Create Post', array('id' => 'submit-post', 'class' => 'btn btn-success btn-lg btn-block', 'style' => 'margin-top: 20px;'))}}
        {!! Form::close() !!}

    </div>
</div>

Ajax Code:

    $(document).on('click', '.create-post', function() {
        $('.create-form').css('display','block');
        $('.posts-table').css('display','none');
    });

    $('#submit-post').click(function(e) {
        e.preventDefault();
        var action = $('#form-post').attr('route');
        var title = $("#form-post").find("input[name='title']").val();
        var slug = $("#form-post").find("input[name='slug']").val();
        var category_id = $("#add-category").val();
        var featured_image = $("#add-image").val();
        var body = $("#add-body").val();


        $.ajax({
            type : 'POST',
            url : "/addpost",
            headers: {
                'X-CSRF-TOKEN' : $('input[name="_token"]').val()
            },
            data : {
                title: title, 
                slug: slug, 
                category_id: category_id, 
                featured_image: featured_image, 
                body: body
            },
            success: function(data){
                $('.create-form').css('display','none');
                $('.posts-table').css('display','block');
                $('.table tbody').append("<tr id='" + data.id + "' class='item'><th>" + data.id + "</th><td>" + data.title + "</td><td>" + data.body + "</td><td>date</td><td><button class='show-modal btn btn-success' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-eye-open'></span> Show</button><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-edit'></span> Edit</button><button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-title='" + data.title + "' data-slug='" + data.slug + "' data-category='" + data.category_id + "' data-image='" + data.featured_image + "' data-body='" + data.body + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
                console.log(data); 
            }


        });

    });
  • 写回答

1条回答 默认 最新

  • Memor.の 2018-04-19 09:46
    关注

    It's not enough information about the error. Try dd() in your controller & check it in [F12 -> Network].

    And since you're using ajax to sending request, there no need to define options (action, route) in Form. remove it.

    评论

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因