Uploading Files Using Ajax to a PHP Class

Having some trouble with my file upload using AJAX to post to an object-oriented PHP class.

Here's the AJAX code:

 var handleUpload = function(event) {
    event.preventDefault();
    event.stopPropagation();

    var fileInput = document.getElementById('file');
    var data = new FormData();

    for(var i = 0; i < fileInput.files.length; i++) {
        data.append('file[]', fileInput.files[i]);
    }

    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function(event) {});
    request.upload.addEventListener('load', function(event) {});
    request.upload.addEventListener('error', function(event) {});

    request.open('POST', 'profile.php');
    request.setRequestHeader('Cache-Control', 'no-cache');
    request.send(data);
}

window.addEventListener('load', function(event) {
    var submit = document.getElementById('submit');
    submit.addEventListener('click', handleUpload);
});

Below is the PHP code calling a function in my created class. The JavaScript posts successfully, but the $_FILES array isn't set, so the PHP if statement doesn't run.

if(!empty($_FILES['file']) && isset($_POST['special'])) {
    $special = $_POST['special'];
    $date = $_POST['date'];
    $user->postSpecial($special, $date, $_FILES);
}

Answer №1

Sending Form Data to a Hidden iFrame

A useful workaround, as recommended by @nietonfir, involves sending form data to a hidden iFrame when using input=file and XMLHTTPRequest is not an option or preferred. While XHR2 may not be supported or desired, it's still possible to achieve this functionality by posting the form to a hidden iframe within the webpage. Various JavaScript libraries and jQuery plugins offer solutions for this (check out https://github.com/Widen/fine-uploader for an example), making the process straightforward.

Answer №2

When your AJAX call fails, it's because files can't be submitted asynchronously, which is why the $_FILES array ends up empty. One workaround for this issue is to use the iframe form post hack or switch to jQuery and utilize the awesome jQuery file upload plugin.

* This limitation is highlighted in XMLHttpRequest2. You can check browser support for this feature at http://caniuse.com/#feat=xhr2.

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

Is there a way to trigger an Axios response without repeated calls or the use of a button?

As I navigate my way through using react and Axios, I encountered an issue with a get request in my code. Currently, I have a button that triggers the request when clicked, but I want to eliminate the need for this button and instead have the information d ...

Redirecting CORS in Cordova: A Comprehensive Guide

My Cordova/Phonegap app is encountering an issue while trying to retrieve certain files using AJAX. The specific error message that I receive states: XMLHttpRequest cannot load https://docs.google.com/uc?export=open&id=.... Redirect from 'https ...

Retrieve checkbox selected value using pug and node.js

How can I retrieve the value of a checked checkbox in order to redirect to (href="/player/edit/:id") or (href="/player/delete/: id"), and obtain the player id for editing or deleting? I have omitted other code details such as app.js which includes the ser ...

Storing data from multiple pages onto the final page using C# and ASP.Net - step-by-step guide!

I need assistance with saving an application that spans across multiple pages. Instead of saving after each step, I would like to review a summary of all the pages on the final page before saving the complete application. Can someone please guide me throug ...

Implementation issue with Hashids library in Vue.js causing functionality hiccups

I'm having trouble getting the library hashids to cooperate with vue.js The method I would like to use is: <template> <div class="container"> {{ hashids.encode('1') }} </div> </template> <script& ...

There was an issue serializing the `.product` data that was returned from `getStaticProps` in the "/prints/[name]" route in Next.js

My Strapi nextjs application has 2 categories of products. Everything works fine locally, but I encounter an error when trying to build: Error serializing .product returned from getStaticProps in "/prints/[name]". Reason: undefined cannot be se ...

The note-taking app's JavaScript code does not currently have the capability to store notes in local storage

const noteContainer = document.querySelector(".note-container"); const createBtn = document.querySelector(".btn"); let notes = document.querySelectorAll(".input-box"); function showNotes() { noteContainer.innerHTML = localS ...

Setting up a nodejs application on a web server

As a newcomer to NodeJS, I am currently learning how to create a sample app using this technology. I have successfully tested it on my localhost, but now I am facing issues when trying to host it on a public server. var http = require('http'); ...

What should be passed as the URL parameter in the ajax function call?

I am currently working with the Codeigniter framework and following the MVC structure. I am facing an issue with determining what needs to be included in the URL for an AJAX call. Below is the snippet of my AJAX call: $.ajax({ url: //<--what should b ...

How can I allow users to select multiple files with just one input?

Currently, I am able to retrieve a single file from a single input using the following code: $scope.$on("fileSelected", function (event, args) { $scope.$apply(function () { $scope.files.push(args.file); ...

Managing the expiration time of a Cookie with ngx-cookie-service: Explained

Currently, I am utilizing ngx-cookie-service in my Angular application. According to the official documentation, it is mentioned that a third parameter can be added for defining the expiration time as shown below: this.cookieService.set('CookieName&ap ...

The Data from Req.Body Doesn't Appear After Adding Form Fields

I've been struggling to find a solution to this issue, but here's the gist of it: I have a button that allows users to add a question and answer pair one at a time by clicking on an "Add Question" button. This is achieved through the append featu ...

I am having trouble with updating an array in React useState. Every time I try to make changes, it keeps reverting back to the initial state. What could

My current task involves managing a state array called monthlyIncidents, which contains 12 numbers that need to be updated under certain conditions. I attempted to update the elements by copying the array, modifying the specific element, and then updating ...

Using the click function in React to narrow down the component map

Currently, I'm working on an exciting project and I've encountered a bit of a challenge that has me stumped. I'm using Axios to fetch data, then rendering it with a .map function. After that, I have a click function that should display only ...

Following the submission of a POST request, an error occurred stating: "Unable to assign headers once they have been sent to

I'm having trouble figuring out what's wrong with my code. Whenever I send a post request, I get an error message saying "Cannot set headers after they are sent to the client". My model includes a comment schema with fields for user, content, and ...

Display the Express response in an HTML element by utilizing the fetch API

I am currently developing a small node/express project that showcases the bcyrpt hashed value of user input. While I have been successful in displaying the hashed value in the server's console.log, I am facing difficulties in injecting this value into ...

The AJAX call in PHP is echoing JavaScript code that seems to be malfunctioning

Currently working on an AJAX page using php, where I plan to output a section of JS code upon completion. Despite having the JS code within the HTML page, it is not functioning properly. Any suggestions on how to get it to work? ...

Can AJAX be exploited by hackers?

Today, I had a fascinating experience with my built systems. Someone managed to "hack" into everything and attributed the issue to AJAX. Here are his exact words: you are relying on AJAX when I have access to user's browser I have acc ...

Improper comment placement in Rails with AJAX and JQUERY

I am developing a "comment system without page refreshing" using Jquery and Ajax. Within posts/show.html.erb <%= @post.title %> <%= @post.body %> <%= render 'comment %> posts/_comment.html.erb <%= link_to "Add Comment", new_po ...

What are the reasons behind the lack of smooth functionality in the Bootstrap 4 slider?

My customized bootstrap4 slider is functional, but lacks smoothness when clicking on the "next" and "prev" buttons. The slider transitions suddenly instead of smoothly. Any suggestions on how to fix this? Here is the code for the slider: $('.carous ...