beginner_luck's avatar

Image Upload using Laravel and ajax.

Hello, can someone help me on how to include in the form a field for image upload using laravel and ajax? It seems like my code for image upload is not working, but the other field works perfectly. Thank you in advance. This is my code.

My Ajax code:

//Ajax call for POSTS // add a new post

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

    $(".link-button").click(function () {
    window.location.href = $(this).data('href');
    });

    $('#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){
                toastr.success('Successfully Added Post!', 'Success Alert', {timeOut: 4000});
                $('.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>" + data.created_at + "</td><td><button class='btn btn-outline-primary link-button' data-href='{{URL::to('posts/{$id}')}}'>View</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></td></tr>");
                console.log(data); 
            }


        });

    });

My Controller:

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|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ));

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

}
0 likes
18 replies
jlrdw's avatar

I typed in upload image with Ajax and some Answered results came up. In fact one of the previous post was a best answer from me.

2 likes
biishmar's avatar
biishmar
Best Answer
Level 11

@beginner_luck

cache: false,
contentType: false,
processData: false,

use this in ajax option and create form data object and append all value into form data.

1 like
beginner_luck's avatar

Hello @biishmar is this right?

    $('#submit-post').click(function(e) {
        e.preventDefault();
        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")[0].files[0];
        var body = $("#add-body").val();
        new form = new FormData();
        form.append('title', title);
        form.append('slug', slug);
        form.append('category_id', category_id);
        form.append('featured_image', featured_image);
        form.append('body', body);


        $.ajax({
            type : 'POST',
            url : "/addpost",
            headers: {
                'X-CSRF-TOKEN' : $('input[name="_token"]').val()
            },
            cache: false,
            contentType: false,
            processData: false,
            data : form,
            success: function(data){
                toastr.success('Successfully Added Post!', 'Success Alert', {timeOut: 4000});
                $('.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>" + data.created_at + "</td><td><button class='btn btn-outline-primary link-button' data-href='{{URL::to('posts/{$id}')}}'>View</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></td></tr>");
                console.log(data); 
            }


        });

    });
beginner_luck's avatar

@biishmar how could I transform this code

"<a href='"{{ route('posts.show', $post->id) }}"' class="btn btn-outline-primary">View"

and put this one on my success method

success: function(data) { toastr.success('Successfully Updated Post!', 'Success Alert', {timeOut: 5000}); $('.edit-modal').css('display','none'); $('.posts-table').css('display','block'); $('.item' + data.id).html("" + data.id + "" + data.title + "" + data.body + "" + data.created_at + " Edit"); }

the success method works but when it was being inserted in the table and when I try to click the button view, it doesn't work, I will just need to reload the page inorder the button View will work.

beginner_luck's avatar

@biishmar in my edit a post using ajax, do I also need to add the thing that you have says to me? This one. cache: false, contentType: false, processData: false,

use this in ajax option and create form data object and append all value into form data.

biishmar's avatar

@beginner_luck if u r creating a button for a row, u better create that through controller side and append to table

MarkLL's avatar

Hey @beginner_luck ... just a thought, if you are using $('.edit-modal').click( ... ) to detect the Edit click for your newly added buttons, then this will not work.

Basically the above only works with elements existing when first loaded. Try this instead.

$(document).on('click', '.edit-modal', function(){ 
    // Your Code
});
beginner_luck's avatar

Hello Sir @biishmar Can you help me with this error, please?

Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

This error shows when I try to edit my post, and it seems like it comes with the image. Thank you sir.

Please or to participate in this conversation.