Issue with AJAX POST method failing to upload the file

I'm having trouble incorporating file upload support into my AJAX post function. Can anyone provide some guidance on what I might be missing?

function ajax_post(url, param) {
    if (url.substr(0, 11) == 'javascript:') {
        result = 'Error: form submits to JavaScript function.\n\nFunction cannot be processed when passed off by the onsubmit event handler.';
    } else {
        var xhr = false;
        
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject('Msxml2.XMLHTTP');
            } catch (e) {
                try {
                    xhr = new ActiveXObject('Microsoft.XMLHTTP');
                } catch (e) {}
            }
        }
        
        if (!xhr) {
            var result = 'Error: your browser does not support AJAX.';
            browser_upgrade_notice();
        } else {
            xhr.open('POST', url, true);
            var f = document.getElementById(id_page).getElementsByTagName('form');
            for (var i = 0; i < f.length; i++) {
                if (f[i].compareDocumentPosition(option.submit) == 20) {
                    f = f[i];
                    break;
                }
            }
            var i = f.getElementsByTagName('input');
            var k = 0;
            for (var j = 0; j < i.length; j++) {
                if (i[j].type == 'file') {
                    k++;
                    break;
                }
            }
            
            if (k == 0) {
                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                xhr.send(param);
            } else {
                xhr.setRequestHeader('Content-Type', 'multipart/form-data');
                xhr.setRequestHeader('Cache-Control', 'no-cache');
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                
                var fd = new FormData();
                
                var z = param.split('&');
                for (var j = 0; j < z.length; j++) {
                    var y = z[j].split('=');
                    fd.append(y[0], y[1]);
                }
                
                for (var j = 0; j < i.length; j++) {
                    if (i[j].type == 'file') {
                        fd.append('file_' + j, i[j].files[0]);
                    }
                }
                xhr.send(fd);
            }
            
            if (xhr.readyState == 4) {
                var result = xhr.responseText;
            }
        }
    }
    
    return result;
}

Answer №1

Due to the websites I was browsing only offering incomplete tutorials and feeling fatigued, I completely forgot about utilizing the onreadystatechange.

This script will dynamically navigate through a form while simultaneously handling the upload of each individual file.

UPDATE: Implemented support for the multiple attribute in the file input element.

function ajax_post(url,param)
{
 if (url.substr(0,11)=='javascript:') {result = 'Error: form submits to JavaScript function.\n\nFunction can not be processed when passed off by onsubmit event handler.';}
 else
 {
  var xhr = false;

  if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();}
  else if (window.ActiveXObject) {try {xhr = new ActiveXObject('Msxml2.XMLHTTP');} catch (e) {try {xhr = new ActiveXObject('Microsoft.XMLHTTP');} catch (e) {}}}

  if (!xhr) {var result = 'Error: your browser does not support AJAX.'; browser_upgrade_notice();}
  else 
  {
   xhr.open('POST',url,true);
   var f = document.getElementById(id_page).getElementsByTagName('form');
   for (var i=0;i<f.length;i++)
   {
    if (f[i].compareDocumentPosition(option.submit)==20)
    {
     f = f[i];
     break;
    }
   }
   var i = f.getElementsByTagName('input');
   var k = 0;
   for (var j=0;j<i.length;j++)
   {
    if (i[j].type=='file')
    {
     k++;
     break;
    }
   }

   if (k==0)
   {
    xhr.send(param);
   }
   else
   {
    var fd = new FormData();

    var z = param.split('&');
    for (var j=0;j<z.length;j++)
    {
     var y = z[j].split('=');
     fd.append(y[0],y[1]);
    }

    for (var j=0;j<i.length;j++)
    {
     if (i[j].type=='file')
     {
      for (var m=0;m<i[j].files.length;m++)
      {
       fd.append('file_'+j+m,i[j].files[m]);
      }
     }
    }
    xhr.send(fd);
   }

   xhr.onreadystatechange = function()
   {
    if (xhr.readyState==4)
    {
     var result = xhr.responseText;
     alert('result = '+result);
    }
   }
  }
 }

 return result;
}

Answer №2

You cannot achieve this using XHR. The best approach is to create a hidden iFrame that contains the file upload form and then submit it via JavaScript.

For more information on Ajax file uploads, check out this helpful resource.

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

Challenge Encountered with Create-React-App TypeScript Template: Generating JS Files Instead of TSX Files

Encountering a problem setting up a new React application with TypeScript using the Create-React-App template. Followed the guidelines on the official documentation (https://create-react-app.dev/docs/adding-typescript/) and ran the command below: npx creat ...

Is there a way to instruct Express to refrain from parsing the request's query string?

Is there a way to turn off Express's default behavior of parsing query strings and ignore them completely? I parse the query strings on the client side, and receiving a large number of requests with long query strings would be resource-intensive for t ...

The form within the dynamically loaded AJAX content is malfunctioning

My webpage is set up to load content from a separate file (content.php) into a div and refresh it every 5 seconds. In the content.php file, I have a form (basic HTML without javascript) that works fine when accessed directly at (example.com/content.php). ...

Using JavaScript to convert the text within a div into negative HTML code

I am working with this specific div: <div class="signs" id="signs" onclick="toggle()">&#43;</div> It currently displays the positive sign. I have set up a JavaScript function that is triggered when the div is ...

How to implement jquery select functionality on clickable table rows?

I've come across a challenge while trying to implement clickable table rows with the jquery selectable function. Everything works perfectly fine with li elements, but I seem to hit a roadblock when using tables - the click event just stops working. Wh ...

Learn how you can efficiently send a JSON response to an AJAX call by utilizing a serialized object along with HTML generated from the Html

Using C# and MVC, I am working on responding to an ajax call triggered by Jquery. My goal is to send back an object that includes a List<int> as well as some HTML code generated using a HtmlHelperExtension that I developed. Previously, I was only se ...

Transforming all commas to plus signs in a JavaScript codebase for the entirety of

Currently, I am using winston for logging and have created a common method to log throughout the project. However, I am facing an issue with many logging statements that look like this: logger.info("here is the data" , data) The problem arises when trying ...

Tips for wrapping a function call that may occasionally involve asynchronous behavior to ensure it runs synchronously

I am dealing with a function that functions as follows: _setDataChunk: function (action) { var self = this; /* some code */ var data = self._getDataChunk(action); populateWidget(data); } Sometimes GetDataChunk cont ...

How to properly size a child div inside a parent container

I'm having trouble with sizing a child div inside a parent div. The problem is that the child div's size changes according to the number of elements it contains, but I want all the child divs to be the same size regardless. This issue arises with ...

Creating a JavaScript function using jQuery to calculate the total sum of textboxes with two specified classes

I'm currently attempting to calculate the total of a group of textboxes by utilizing jquery. Each textbox is styled with a class (class1) using bootstrap. To execute the jquery function, I've added an extra class (class2). Below is an example of ...

Utilize jQuery to dynamically load and assign unique ids to elements within an array

I am seeking assistance with dynamically assigning unique IDs to elements in an array using JavaScript and jQuery. I am new to these languages and need some guidance. function assignIds() { var elementIds = ['name', 'lname', ' ...

Unable to instantiate a class using a module in React

I am on a mission to combine Monaco editor and Convergence in order to create a collaborative editor. To achieve this goal, I am referencing the following repositories and examples: https://github.com/convergencelabs/monaco-collab-ext https://github.com/c ...

Creating a well-aligned form using Material-UI

Exploring Material-UI for the first time! How can a form be built where certain fields are arranged horizontally, others stacked vertically, and all aligned perfectly both vertically and horizontally? Check out this example image: https://i.sstatic.net/5R ...

In NextJS, where is the best place to run sensitive code to ensure it is only executed server-side?

I'm currently exploring the world of NextJS and I am in the process of figuring out how to structure my project with a solid architecture that prioritizes security. However, I find myself at a crossroads when it comes to determining the best place to ...

After props have been passed, the ReactJS ComponentWillMount() function is triggered

Can anyone explain why the child component is only rendered once, even though I pass props to it every time I click a button? Whenever I click a button that passes props to the child, the ComponentWillMount() method of the child component doesn't tri ...

Tips for enabling or disabling elements within an array using React JS

I am looking to develop a feature where I can toggle individual boxes on and off by clicking on them. Currently, only one box at a time can be activated (displayed in green), but I want the ability to control each box independently without affecting the ot ...

Is it possible that the background color won't change on the second click?

Initially, my first click worked fine and successfully changed the background color. However, as soon as I added a second condition, it stopped working. var showBox = $('.show'); showBox.click(function(){ if (parseInt($(this).attr('v ...

Creating a serial number in a Class without relying on a global variable is a useful technique that

I am looking for a way to assign a unique ID to each instance of a Class without relying on global variables. I have tried using a global variable and incrementing it, but I would prefer a more efficient approach. Is there a way to generate an ID within t ...

Where within Video.js can I modify the color of the large play button when the cursor hovers over the video?

After successfully changing the SCSS $primary-background-color to orange using the video.js default skin editor (CodePen), I encountered an issue. Whenever I hover my mouse cursor over the video, the big play button background reverts to its default grayis ...

What are the steps to successfully deploy a static website created with Next.js on Vercel?

Using the Next.js static site generator, I created a simple static site that I now want to deploy on Vercel. However, I keep encountering an error during the build process. While I have successfully deployed this site on other static hosting platforms befo ...