Image Upload using Laravel and ajax.

Published 3 months ago by beginner_luck

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

}
Best Answer (As Selected By beginner_luck)
biishmar

@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.

jlrdw
jlrdw
3 months ago (237,650 XP)

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.

biishmar

@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.

beginner_luck

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


        });

    });
biishmar

@beginner_luck yup thats right try dd in controller and check.

beginner_luck

Oh, Thank you very much @biishmar it is now working, I can upload an image now.

biishmar

@beginner_luck good luck on your project and mark it solved

beginner_luck

@biishmar If you don't mind, can I ask you one last question?

biishmar

@beginner_luck this place is meant to ask questions, go on i dont mind

beginner_luck

@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.

biishmar

@beginner_luck create that view button from controller and send it to ajax so u can append to your table.

beginner_luck

@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

@beginner_luck after u storing that data , are you appending that info to table in same page?

beginner_luck

@biishmar yes sir, in the table of the same page.

biishmar

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

MarkLL

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

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