beginner_luck's avatar

Ajax call with Laravel form

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


}
0 likes
15 replies
Snapey's avatar

Why not

$('body').on('click', '#submit-post', function(e) {

replace with

$('#submit-post').click(function(e) {

and check the browser console for errors

1 like
beginner_luck's avatar

@Snapey this error will shows me

Error:

Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)

rin4ik's avatar
rin4ik
Best Answer
Level 50

you have to include csrf token

1 like
beginner_luck's avatar

Yes sir @rin4ik. Error Shown in Console.

POST http://blog.com/addpost 422 (Unprocessable Entity) POST http://blog.com/addpost 500 (Internal Server Error)

And in my network.

{message: "The given data was invalid.",…} errors

{featured_image: ["The featured image must be an image."]} featured_image

["The featured image must be an image."] 0

"The featured image must be an image." message

"The given data was invalid."

rin4ik's avatar

you have now validation errors . includeenctype="multipart/form-data" to your form when you want to upload image

1 like
beginner_luck's avatar

When I try to put a data in the form without putting an image on it, my data will saved in the database and it is working. I think my problem here is my image upload field.

jlrdw's avatar

Clear browser and all temp view file cache in between coding. You may have correct code but would never know what's going on without that cache being cleared.

1 like
beginner_luck's avatar

Is there any other way on how I can include an image upload field and works using laravel and ajax,it seems like my problem was in my image upload, because when I don't put an image it is working perfectly, but when i put it doesn't.

jlrdw's avatar

I am not on desktop now but if you search a while back someone ask about upload with Ajax and there was a pretty good answer.

1 like

Please or to participate in this conversation.