Ajax call with Laravel form

Published 1 month 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);


}
Best Answer (As Selected By beginner_luck)
rin4ik

you have to include csrf token

beginner_luck

Thank you @ekhlas, I am done replacing it. But my submit button still not working.

Snapey
Snapey
1 month ago (866,905 XP)

Why not

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

replace with

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

and check the browser console for errors

beginner_luck

@Snapey this error will shows me

Error:

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

rin4ik
rin4ik
1 month ago (178,120 XP)

you have to include csrf token

beginner_luck

Thank you @rin4ik I will update my code here.

rin4ik
rin4ik
1 month ago (178,120 XP)

@beginner_luck still 422 error?

beginner_luck

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
rin4ik
1 month ago (178,120 XP)

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

beginner_luck

Still not working but the validation error was gone.

rin4ik
rin4ik
1 month ago (178,120 XP)

here is how you can check the request. watch this please https://d.pr/free/v/7ju99R. what error do you have after that check

beginner_luck

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
jlrdw
1 month ago (215,530 XP)

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.

beginner_luck

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
jlrdw
4 weeks ago (215,530 XP)

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.

beginner_luck

Thank you for your help guys, @jlrdw @rin4ik @Snapey @ekhlas Finally it is now working.

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