Ajax call with Laravel form

Posted 9 months ago by beginner_luck

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

Form Code:

Create New Post

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


        });

    });

PostController Code:

public function store(Request $request)
{
    $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'
    ));

    $post = new Post;

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

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


}

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.