Laravel and jQuery: Seamlessly Uploading Images with AJAX

I have been facing issues while trying to upload photos in Laravel using jQuery AJAX. I keep encountering an error message:

The photo must meet the following criteria: - The photo must be an image. - The photo must be a file of type: jpeg, png, jpg, gif, SVG.

I am perplexed as to why this is happening. What could possibly be wrong with my code below?

Controller Section

I have used the code snippet below to handle the photo uploading process, but it seems to be causing errors multiple times:

$validator = \Validator::make($request->all(), [
    'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
    
if ($files = $request->file('image')) {
    //---Insert new file
    $destinationPath = 'public/product_images/'; // upload path
    $image_path = date('YmdHis') . "." . $files->getClientOriginalExtension();
    $files->move($destinationPath, $image_path);
}

$productId = DB::table('products')->insertGetId([
    'product_photo' => $image_path
]);

View Section

In the view section, the following code is used to implement the functionality for uploading the photo:

$("#photo").fileinput({
    theme: 'fa',
    uploadUrl: '{{ route('products.store') }}',
    uploadExtraData: function() {
        return {
            _token: $("input[name='_token']").val(),
        };
    },
    allowedFileExtensions: ['jpg', 'png', 'gif'],
    overwriteInitial: false,
    maxFileSize: 2000,
    maxFilesNum: 5,
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});
                        
$('#saveBtnForCreate').click(function(e) {
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        url: "{{ route('products.store') }}",
        method: 'post',
        enctype: 'multipart/form-data',
        cache: false,
        dataType: 'JSON',
        data: {
            photo: $('#photo').val()
        },
        success: function(result) {
            if (result.errors) {
                $('.alert-danger').html('An error has occurred in your input!');
                $.each(result.errors, function(key, value) {
                    $('.alert-danger').show();
                    $('.alert-danger').append('<strong><li>' + value + '</li></strong>');
                });
            } 
        }
    });
});

Answer №1

It seems that the file you uploaded does not comply with the validation rules. Additionally, there is an error in your code on the line `` where you are attempting to save image instead of photo. The following code snippet is extracted from the Laravel documentation for storing files.

$validator = \Validator::make($request->all(), [
    'photo' => 'required|file|mimes:jpeg,png,jpg,gif,svg',
]);
if ($files = $request->file('photo')) {
    // Add new file
    $destinationPath = 'public/product_images/'; // Specify upload path
    $image_path = $request->file('photo')->store($destinationPath);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: A boolean type cannot be used as a function in the fullcalendar ajax call

I have successfully implemented a fullcalendar into my app and have added a method to filter results by user: function filterEventsByProvider(selected_provider) { $('#calendar').fullCalendar('removeEvents'); $('#calendar&a ...

Transfer information to the form through a hyperlink

I need help with a script that sends data to a form when a link is clicked. What I'm trying to achieve is to have the data appear in the form when the user clicks the link below, which is generated from a database. <div id="menu_bar" region="west ...

Is there a way to automatically remove the upload button after the file has been successfully uploaded?

I'm currently using blueimp and jquery UI to handle file uploads. My goal is to dynamically hide a specific button once a file is uploaded, and then display it again if the photo is removed. How can I achieve this functionality? https://i.stack.imgu ...

Transform an HTML table string into JSON format

I discovered a useful library called table to JSON that allows me to convert an HTML Table to JSON using its ID (#testtable in the example below): var table = $('#testtable').tableToJSON(); alert(JSON.stringify(table)); However, I am interested ...

Is there a way to load information retrieved from an API into a dropdown menu in Laravel with the help of VueJS and axios?

After many attempts, I still can't seem to fetch my API data into a select list successfully. Everything seems to be retrieved properly, but when it comes to displaying them, nothing shows up. Could there be an issue with my code? Here's my rout ...

Restrict the duplication of div elements with JQuery

Here is the structure I'm working with: <div class="checkmark-outer"> <div class="checkmark-33"> <div class="fa-stack fa-1x checkmark-icon"> <i class="fa fa-circle fa-stack-2x icon-background"></i> ...

What is the best way to align these div elements within a table cell?

I am encountering an issue with the placement of elements. What I am striving for is something like this: https://i.stack.imgur.com/VSFXE.png where a div with several other divs inside is positioned at the top of the td, and another div is at the bottom o ...

One simple click to auto-fill the form

I have encountered a problem that has been discussed before, but my lack of coding knowledge is making it difficult for me to find a suitable solution that matches the code on my website. The issue at hand is as follows: I need my form to populate car mak ...

Invoke a confirmation dialog with onBeginForm() function prior to initiating OnSuccessForm() in Ajax.BeginForm

Once a selection of 'Yes' or 'No' has been made on the confirmation dialog, the OnSuccessForm() function appears to not be triggered. Is there a way to pause the onBeginForm() process before moving forward? My MVC3 Form @using (Ajax.B ...

Exploring how to locate an item in an array using its id with Underscore

Here is an array of objects showcasing equipment images: var jsonarray = [{ "id": "6", "equipment_img": "http://xxx:9696/XXX/images (1)_410.jpg" }, { "id": "7", "equipment_img": "http://xxx:9696/XXX/5.jpg" }, { "id": "8", "equipmen ...

Unraveling the Enigma of Event Handlers: Mastering the Organization of a Sprawling jQuery File within an AJAX

I've created a web application that heavily relies on AJAX and jQuery for DOM manipulation and making AJAX requests. However, I'm facing a problem with my JavaScript file: The issue is that my JavaScript file consists of a huge collection of eve ...

Obtaining a return value from a function that involves a series of chained Ajax requests in jQuery

I'm facing an issue with my function that involves chained Ajax requests. Function A and B are both Ajax requests, where A runs first and B runs after A returns its data. The problem arises when Function C executes Function B. Upon execution of Funct ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...

Enhance your data table by updating the content without the need to refresh the entire page in CodeIgniter

Every time I update or insert data using the bootstrap modal form and ajax, the entire page reloads. Instead of refreshing the whole page, I want only the data table to be refreshed. Below is my ajax script: <script> $(document).ready(function( ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

Leveraging the power of Jackson in Spring MVC 2.5

Apologies for the vague question, but my searches have been unfruitful. Our project uses Spring MVC 2.5, which lacks the @ResponseBody annotation. Is there a way to achieve something similar to this without it? ...

The functionality of a custom control's jQuery code is not functioning properly following a postback

I'm currently developing a custom control that generates jQuery validation scripts for controls with changing validation rules based on configuration. It's necessary for the validation to be client-side due to large postbacks and slow, low-bandwi ...

Identify all td inputs within a TR element using jQuery

Is there a way to retrieve all the input values within each table cell (td) of a table row (tr) using jQuery? Suppose I have a tr with multiple td elements, and some of these tds contain inputs or select elements. How can I extract the values from these in ...

Move from right to left on the slide?

Is there a way to toggle a div's visibility between collapsed and expanded, transitioning smoothly from right to left? I've noticed that most examples I come across demonstrate the transition from left to right. ...

I need to know how to send a "put" request using JavaScript and Ajax

My task involves programmatically updating a spreadsheet using my code. I am able to write to a specific cell within the spreadsheet with the following function: function update(){ jQuery.ajax({ type: 'PUT', ...