What is the best way to add numerous images to a Laravel platform via ajax using pure javascript?

I am currently working on a form where users can upload one or more photos to the server using ajax. Sometimes, users may not upload any photos at all. How can I efficiently send the data from the file input to the server in the background?

Below is the relevant section of the form:

<form action="" method="POST" enctype="multipart/form-data>
            @csrf
                <label for="photos">Photos:</label>
                <input type="file" name="photos[]" id="photos" class="form-control" multiple>

                <button class="btn btn-success mt-3" onclick="ajaxify(event)">Submit</button>
            </div>
        </form>

And here is the relevant part of the JavaScript code:

function ajaxify(event) {
            event.preventDefault();
            let failedValidation = false;

           // Some parts of this code have been omitted for clarity.

            let photos = [];


            if(document.getElementById('photos').value !== '') {
                photos = document.getElementById('photos');   // This part needs correction.
            }

           // The current implementation only returns one file path like c://fake/filename,
           // and it does not handle multiple file uploads correctly.

            if(!failedValidation) {
                axios.post('/listing/create', {
                    client_name: name.value,
                    // Other data fields omitted for brevity.
                    photos: photos.value, // Incorrect handling of uploaded files.
                })
                .then((resp) => {
                    invalid.classList.add('d-none');
                    console.log(resp);
                })
            }
        }

Goal: My objective is to have the uploaded files available to Laravel on the server side so that I can process them with a normal post request and retrieve the array of uploaded files using dd($request->photos);. I am not sure if this functionality can be achieved using ajax/json, but it would greatly help in processing the photos.

A quick note, I am utilizing the Laravel media library package for this project.

Progress: Upon researching, I found suggestions to use FormData(). However, I have some questions regarding its usage. Should all data be included in the FormData() object and passed to axios? Or is it specifically required for handling photos? I have yet to implement either approach and would appreciate any guidance on this matter.

Answer №1

When retrieving files, remember that they are stored in an array within the files attribute. To include them in your photos array, simply append them.

function ajaxify(event) {
  event.preventDefault();

  // access an array of files using the files attribute
  var photoFiles = document.getElementById("photos").files;

  // create an array of FormData objects called 'photos' using the file array
  let photos = [];
  for (let photo of photoFiles) {
    photos.push(new FormData(photo);
  }

  // transform your 'photos' array into a javascript object
  let photos = arr2obj(photoFiles);

  // by passing 'photos' to the ajax data, you should resolve the empty array issue

  // ....
}

EDIT: As indicated in this post, a FormData object is mandatory for AJAX file uploads. Hence, ensure that your array consists of FormData objects.

EDIT: Transmitting arrays via JSON can be problematic. Convert your array into an object instead. You can utilize a simple function like this to construct an object from the array.

function arr2obj(arr) {
  var obj = {};
  for (let i=0; i<arr.length; i++) {
    obj['photo'+i] = arr[i];
  }
  return obj;
}

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

In the tutorial for creating a basic web application, an issue arises with AWS Lambda stating that it "cannot locate module aws-sdk"

As I embark on my AWS journey, I decided to start from scratch by following the Build a Basic Web Application tutorial. Everything seemed straightforward until I encountered an unexpected error while trying to include the basic aws-sdk module! In Brief: ...

Is it possible for node-java to accept anonymous functions as parameters in Java?

I am looking to pass an anonymous function from JavaScript to Java using node-java (https://github.com/joeferner/node-java). Below is a snippet of the Java code for reference: public class Example { public Example() { } public interface Callb ...

What is the best way to incorporate a JSON file into a JavaScript class?

I attempted to load a JSON file within a JavaScript class, but encountered an issue where the loaded data was only accessible inside a specific function. class CreatePage { constructor() { var request = new XMLHttpRequest(); request. ...

Utilizing HTTP POST method in vanilla JavaScript with AJAX

Having some trouble sending a post request to my PHP file as it keeps saying 'undefined index'. Here is my JavaScript code: document.getElementById("btn1").addEventListener('click', xh ); function xh(){ xhr = new XMLHttp ...

Extract JSON from the response data in the success callback of a JQuery.ajax

I've encountered an issue with retrieving the contents of a JSON object from a JQuery.ajax call. Here is my code: $('#Search').click(function () { var query = $('#query').valueOf(); $.ajax({ url: '/Products/Se ...

Exploring the combination of React, Redux, and Saga for server-side rendering, along with addressing the challenge of preventing unnecessary AJAX calls on a page

Currently, I am engaged in a web development project that incorporates server-side rendering using Node.js, Express, and React. To handle data fetching and state management with Redux, we utilize Redux-Saga. However, we are facing an issue where our applic ...

(basic) Issue with Jquery ajax request not receiving data

The alert box is not displaying anything and is not returning any data from the specified URL, even though it should show the Google page! Any suggestions? I am using the POST method because I need to send querystring data as well. $.ajax({ ...

Altering the backdrop upon hovering over an element

As a beginner in Javascript and Jquery, I am working on creating an interactive feature where hovering over one element changes the background image in another column. I have managed to write the function, but now I want to add an animation to the image tr ...

Issue with jQuery autocomplete not showing retrieved data from Ajax request

After implementing an Ajax call within a jQuery autocomplete source function, I observed that the data is being returned to the view in the correct format when checking with tools like Fiddler and Chrome's Network console. However, despite the succes ...

Error: Unable to assign a value to the length property of [object Object] due to it having only a getter method during the conversion process

Here is the code snippet that I am currently using with Node version 4.2.5 and [email protected] xls-to-json. function convertXLStoJSON(inputfile, outputfile, sheetName) { node_xj = require("C:/Protractor_Scripts/node_modules/xls-to-json"); no ...

react native is not updating the view even though the state has been changed

Upon opening my component, I am looking to retrieve Assets from a Media Folder (which is currently functional) and then pass them along to another component. However, the issue arises when launching the app for the first time, as the "listOfAssets" state a ...

Tips for troubleshooting common network errors in Volley

When attempting to access this function through WiFi, it works fine. However, when using a mobile network, I encounter the following error: D/Volley: [3641] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] 0x95bac5ee NORMAL 14> * 2020-0 ...

Is it possible to receive both errors and warnings for the same ESLint rule?

My team is currently in the process of refactoring our codebase, utilizing ESLint to pinpoint any lint errors within our files. Initially, we set high thresholds in one .eslintrc file and have been gradually decreasing these limits as we enhance specific f ...

Display an image with only a portion visible, no canvas, no frame, and no need

My dilemma involves an img with a surrounding box div. http://jsfiddle.net/6d4yC/7/ 1) I am seeking to display only a portion of the image (250x150) without generating a white overlay when it is in its large size. Placing a #box1 div around the image has ...

What is the best way to add content in JavaScript?

Just diving into the world of JavaScript, HTML, and web development tools here. var labels = {{ labels|tojson|safe }}; After using console.log to check the content of labels with console.log(JSON.stringify(labels));, I got this output: [ {"id":"1", ...

When using JSX, it's important to wrap adjacent elements within an enclosing tag to avoid errors. Make sure to properly wrap the JSX tags to

import React, { useState } from 'react'; import ReactDOM from 'react-dom'; function DisplayData(props) { //creating the DataList const dataList = data.map(data => ( <><span>{data.name}</span> nbsp; <span> ...

What is the best way to include bootstrap using webpack?

I am currently building a webapp using Typescript and webpack. I have been able to successfully import some modules by including them in my webpack.config.js file as shown below. However, no matter how many times I attempt it, I cannot seem to import the b ...

Determine if a JSON object is void

Using jQuery, I am checking whether the object returned from an AJAX call is empty or not. In the first example, the AJAX call is successful and returns some data. console.log("obj before JSON parse:", response); var test = $.isEmptyObject(response); con ...

The updates made to a form selection using Ajax do not reflect in jQuery's .serialize or .val functions

When using the .load jQuery function to retrieve a form and place it in the document body, I encounter an issue. After loading the form, I manually change the select value and attempt to save the form using an ajax .post request. However, when trying to ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...