Having issues uploading a file through ajax

I have encountered an issue with my CGI for uploading files. It works perfectly fine when using the <form> tag to upload files, but seems to fail when attempting to send data via ajax...

The form code looks like this:

<form id="confUpdate" enctype="multipart/form-data" method="post" action="upload.cgi">
    <input id='upLoad' type='file' name="file">
    <input id='btnUpload' type="submit" name="send" value="Upload">
</form>

It functions properly if I just leave the button type as 'submit'.

However, when I change the button type from 'submit' to 'button' and try to handle it with JavaScript:

window.onload=function(){
    var upfile=document.getElementById("upLoad");
    var upform=document.getElementById("confUpdate");
    var btnUpload=document.getElementById("btnUpload");
    var info=document.getElementById("InfoText");
    var xhr;
    btnUpload.onclick=function(){
        var file=upfile.files;
        var formData=new FormData();
        if(file[0].name.split(".")[1]!="bin"){
            info.innerHTML="The file should be a .bin file.";
        }else{
            info.innerHTML="";
            formData.append("file",file[0],file[0].name);
        }
        if (window.XMLHttpRequest) {
            xhr=new XMLHttpRequest();
        }else{
            xhr=new ActiveXObject("Microsoft.XMLHTTP");
        }
        try{
            xhr.open('POST', 'upload.cgi', true);
            xhr.setRequestHeader("content-type","multipart/form-data");
            xhr.onreadystatechange = onReceive;
            xhr.send(formData);
        }catch(e){
            xhr.abort();
        }
    }

    function onReceive(){
        var xml;
        var elem;
        if(xhr.readyState==4){
            if(xhr.status==200){
                xml=xhr.responseText;
                info.innerHTML="Uploaded:" + xml;
            }else{
                info.innerHTML="There was an error.";
            }
        }
    }
}

Upon clicking the button, the debug text simply displays 'Uploaded:', indicating that the file data is being sent, but the XML response from the server side remains empty.

I'm unsure whether the issue lies with my server-side code or my JavaScript implementation?

My guess is that the file should be named 'file'.

Any guidance or suggestions would be highly appreciated!

Answer №1

I finally figured out the issue!

After examining the upload API, I discovered that I also need to include the name of the button!

Here's the updated AJAX code:

            var upfile=document.getElementById("upfile");
            var upform=document.getElementById("upform");
            var btnUpload=document.getElementById("btnUpload");
            var info=document.getElementById("InfoText");
            var xhr;

            upform.onsubmit = function(event){
                event.preventDefault();

                info.innerHTML="";

                var files=upfile.files;
                var formData=new FormData();
                if(files[0].name.split(".")[1]!="bin"){
                    info.innerHTML="The file should be .bin file.";
                }else{
                    info.innerHTML="Uploading, please wait.";
                    formData.append("file",files[0],files[0].name);
                    formData.append("send","Send");

                    if (window.XMLHttpRequest) {
                        xhr=new XMLHttpRequest();
                    }else{
                        xhr=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    try{
                        xhr.open('POST', 'upload.cgi', true);
                        //xhr.setRequestHeader("Content-Type","multipart/form-data");
                        xhr.onreadystatechange = onReceive;
                        xhr.send(formData);
                    }catch(e){
                        xhr.abort();
                    }
                }
            }

            function onReceive(){
                var xml;
                var elem;
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        xml=xhr.responseText;
                        info.innerHTML="Uploaded:"+xml;
                    }else{
                        info.innerHTML="Something is error.";
                    }
                }
            }

I can't believe I overlooked the importance of including the button's name when uploading a file!

A huge thank you to everyone who provided me with advice!

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

Using JavaScript to access the Wikipedia API with the Access-Control-Allow-Origin feature

Currently attempting to retrieve a response from the Wikipedia API on Codepen. The expected reply should be in json format, which I plan to display using console.log. However, when checking the console, I encounter an error: Cross-Origin Request Blocked: ...

Ways to filter and display multiple table data retrieved from an API based on checkbox selection in Angular 2 or JavaScript

Here is a demonstration of Redbus, where bus data appears after clicking various checkboxes. I am looking to implement a similar filter in Angular 2. In my scenario, the data is fetched from an API and stored in multiple table formats. I require the abili ...

Achieving Consistent Aesthetics Across Java and Javascript Charts

Currently, I am facing a situation where I am showcasing charts on the client side using the Javascript library called Raphael. When users click on download, I want to be able to generate the same chart in PDF format and present it to them. However, the ch ...

Delete an Item from an Array in MongoDB

I'm currently working on a node application where I store information in MongoDB using mongoose. My goal is to use a DELETE request to remove a specific list item from an array stored in the database. Each item in the list is represented as an object, ...

Find the total number of divs with a specific class using jQuery, and then retrieve the id strings of the inner

How can I count the total number of divs by their class name and extract specific parts from their inner div IDs? Here is a sample code snippet: <div class=”my_block1”> <div class=”my_block2”> <div id=”my-style-35-area ...

The function does not have a specified return value

I've been grappling with this issue for quite some time and I can't figure out what's causing the problem. In my code, I have a separate class called Database.js that handles MySQL functions, manages connections, queries, etc. My goal is to ...

The SCORM content is not establishing a connection with the Learning Management System

Despite initializing, the SCORM package is failing to communicate with the LMS and throwing an error: No SCORM implementation found. Below is my folder structure: -index.php -player.php -course/SCORM-course (directory) -wrap.js -SCORM_2004_APIWrapper.js ...

Understanding the distinctions among variables in typescript

Can someone explain the difference in Typescript between "!option" and "option"? It seems like they are not equivalent. const limit = !options.limit || options.limit === NaN ? 0 : options.limit ...

Executing the default function for a successful response when using Jquery's $.post

Is there a way to automatically execute specific functions after every successful completion of a $.post request? For example, currently I have the following code: $.post(ROOT + 'Ajax', { call: 'Enquiry->setEnquiryUrgency', ...

Positioning of Cloned Element in jQuery

When a user presses enter while in one of the text input fields provided, I want to add a new empty text input field directly below it - and before the other existing ones. The code snippet below currently adds the new field at the end of the container, bu ...

An AngularJS error has been caught: [$injector:modulerr]

After implementing AngularJS in my application, I encountered an error when adding a configuration section for routing: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.9/$injector/modulerr?p0=demoApp&p1=Error%3A…nts%2FGitHub%2FS ...

Display solely the error message contained within the error object when utilizing the fetch API in JavaScript

I am facing an issue in logging the error message to the console while everything else seems to be working fine. Specifically, I am unable to log only the message such as "email exists" when the email already exists in the system. const submitHandler = a ...

Unable to operate a playlist application

I am currently facing an issue while trying to run a small application using an HTML kit. The application consists of two forms - one for text input and the other for a button. The goal is to save the text entered in the text input form into a list when th ...

Display the Vaxis line in a bar graph using Google Chart

Currently, I am involved in a project where I need to display a graph that resembles the one depicted here. To accomplish this task, I am utilizing the Google Visualization Chart API. Successfully, I have managed to generate the chart as illustrated below ...

Counting records in a nested ng-repeat using AngularJS

As a newcomer to AngularJS, I am facing an issue with a nested ng-repeat using a custom filter. I want to display the record count of Orders being shown, but when applying a product filter, it does not work as expected. For instance, if an order has no pro ...

Customizing the start and end dates of months in PHP: A step-by-step guide

My pay cycle starts on the 26th of the previous month and ends on the 25th of the current month. For example, for February 2016, the pay cycle would be from January 26 to February 25. I am looking for the following output: $date = '2014-02-27'; ...

Intelligent javascript jQuery element

It's quite intriguing to see how JQuery library works. By delving deeper into the code, one can understand its inner workings. Take a look at this example below - $.prototype.mymethod=function(str){ alert(str); } //now call the added method $(d ...

Challenges with login pages integrating JS/JQuery and Firebase

I've been working on creating a login page where once the user successfully logs in, I want to make it so that they are redirected from the index.html page to my portfolio.html page. firebase.auth().onAuthStateChanged(user => { if(user) { wind ...

"How can I perform a expressjs database query based on a specific user's

app.get('/user/:id', function(req, res){ fetchData(req.params.id, res); }); function fetchData(id, res) { connection.query('SELECT * FROM data WHERE name = ?' , function(err, rows){ res.render('users', {users ...

Is it possible to include array elements in a dropdown menu using React?

Imagine you have an array called const places = [" a1", "a2", "a3"]; and <FormControl variant="outlined" className={classes.formControl}> <InputLabel id="dropdown_label">Testing</InputL ...