There seems to be an issue with the functionality of the AJAX file upload feature in

I've developed a method for file uploading using AJAX technology (pure JavaScript) in CodeIgniter.

Here's how it works:

1- I created a script.js file to manage the AJAX/JavaScript upload process.

2- I implemented a controller in CodeIgniter to handle requests from AJAX for file uploads.

3- I built a simple HTML page.

ISSUE: After clicking the upload button, nothing seems to happen! No errors are displayed. I suspect there's a data transfer issue between JavaScript and PHP. A similar code worked successfully in a regular PHP page.

Here are the files:

This is the JavaScript code:

// JavaScript Document
var doUpload =  function(event){
        // variables used within this function
        var progressBar = document.getElementById('progressBar');

        event.preventDefault(); // stop default action of element
        event.stopPropagation();        
        // get the file-input id
        var fileId = document.getElementById('file');    

        // create object to hold key/value pairs to be sent via ajax.send
        var formObj = new FormData();

        // append selected file to data object            
        formObj.append('file', fileId.files[0]);        


        // variable to check in the PHP script (controller if CodeIgniter is used)
        formObj.append('error-check', true);
        formObj.append('finish-check', true);

        // create the AJAX request object
        var ajaxReq = new XMLHttpRequest();

        // PROGRESS  OF THE FILE /////////////////////////////////////////////
            // function to display progress during file upload

        ajaxReq.upload.addEventListener('progress', function(event){        

                console.log('this is a very good.');        

                // get file load percentage
                var percent = event.loaded / event.total;

                if(event.lengthComputable) // if file is inserted and ready to upload
                {
                    if(progressBar.hasChildNodes()) // clear div container for new progress display
                    {
                        progressBar.removeChild(progressBar.firsChild);
                    }
                    progressBar.appendChild(document.createTextNode('Progress So Far: '+percent*100+' %'));
                }
        // END OF PROGRESS  OF THE FILE /////////////////////////////////////////////



        // LOAD  OF THE FILE /////////////////////////////////////////////
            ajaxReq.upload.addEventListener('load', function(event){
                progressBar.appendChild(document.createTextNode(" Completed!"));
            });
        // END OF LOAD  OF THE FILE /////////////////////////////////////////////

        // ERROR  OF THE FILE /////////////////////////////////////////////
            ajaxReq.upload.addEventListener('error', function(event){
                progressBar.removeChild();
                progressBar.appendChild(document.createTextNode("Failed to Upload the File."));
            });    
        // END OF THE ERROR  OF THE FILE /////////////////////////////////////////////

        // JSON            

        // OPEN THE AJAX REQUEST
        ajaxReq.open('POST', 'upload/uploader');

        // Set the header of the POST request
        ajaxReq.setRequestHeader('Cache-Control', 'no-cache');

        // send the file. remember, we shoud pass a formData object as an argument to the ajaxRequest.send();
        ajaxReq.send(formObj);

        });

}

window.addEventListener('load', function(event)
{    
        // get the submit id
        var submitButton = document.getElementById('submit');
        submitButton.addEventListener('click', doUpload);
});

This is the PHP Controller in CodeIgniter:

<?php
class Upload extends CI_Controller
{
         function index()
        {
            $this->load->view('pages/form');
         }
         function uploader ()
         {
                // define required settings for upload library
                $config['upload_path'] = './uploads/';
                $config['allowed_types'] = 'gif|jpg|png|doc|txt';
                $config['max_size']  = 1024 * 8;
                $config['encrypt_name'] = TRUE;


                // load the upload library
                $this->load->library('upload', $config);


                if(!$this->upload->do_upload('file'))
                {
                    $data['error'] = $this->upload->display_errors();
                    //$this->load->view('pages/form', $data);
                    json_encode($data['error']);
                }
                else
                {
                    $data['uploaded'] = $this->upload->data();
                    //$this->load->view('pages/form', $data);    
                }


         }

}

This is the HTML code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Form With Ajax</title>
<script src="<?php echo base_url(); ?>js/script.js" type='text/javascript'></script>
</head>

<body>
<div id='error' style='color: red;height: 40px; width: 200px;'>
<?php
if(!empty($error)){echo $error; }
?>
</div>
<form id='form' name='form' enctype="multipart/form-data" >
<input type='file' name='file' id='file'/>
<input type='submit' name='submit' id='submit' value='Upload File' />
</form>
<div style='height: 200px; width: 300px; color: red; padding: 10px; background-color: #CCC;' id='progressBar'></div>
</body>
</html>

Answer №1

In the file script.js, move the following code:

// OPEN THE AJAX REQUEST
ajaxReq.open('POST', 'upload/uploader');
// Set the header of the POST request
ajaxReq.setRequestHeader('Cache-Control', 'no-cache')
// send the file. remember, we should pass a formData object as an argument to the xhruest.send();
ajaxReq.send(formObj);

outside of the progress event listener:

    ajaxReq.upload.addEventListener('progress', function(event)
    {        
        console.log('this is a very good.');        
        // first let's get the amount of the file loaded. it is in decimals
        var percent = event.loaded / event.total;
        // get the name of the element that the progress-indicator is outputted there
        if(event.lengthComputable) // if a file is inserted and everything is just OK for uploading
        {
            if(progressBar.hasChildNodes()) // cleans the div container for a new progress to display
            {
                progressBar.removeChild(progressBar.firsChild);
            }
            progressBar.appendChild(document.createTextNode('The Progress So Far: '+percent*100+' %'));
        }
        // END OF PROGRESS  OF THE FILE /////////////////////////////////////////////


        // LOAD  OF THE FILE /////////////////////////////////////////////
        ajaxReq.upload.addEventListener('load', function(event)
        {
            progressBar.appendChild(document.createTextNode(" Completed!"));
        });
        // END OF LOAD  OF THE FILE /////////////////////////////////////////////
        // ERROR  OF THE FILE /////////////////////////////////////////////
        ajaxReq.upload.addEventListener('error', function(event)
        {
            progressBar.removeChild();
            progressBar.appendChild(document.createTextNode("Failed to Upload the File."));
        });    
        // END OF THE ERROR  OF THE FILE /////////////////////////////////////////////
        // JSON            
    });
    // OPEN THE AJAX REQUEST
    ajaxReq.open('POST', 'upload/uploader');
    // Set the header of the POST request
    ajaxReq.setRequestHeader('Cache-Control', 'no-cache')
    // send the file. remember, we should pass a formData object as an argument to the ajaxRequest.send();
    ajaxReq.send(formObj);

Answer №2

Encountering a different issue in my code that hindered the execution: I mistakenly included:

ajaxReq.upload.addEventListener`

The correct approach was to eliminate the upload part:

ajaxReq.addEventListener

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

React js background image not filling the entire screen

Having experience with React Native, I decided to give ReactJS a try. However, I'm struggling with styling my components because CSS is not my strong suit. To build a small web application, I am using the Ant Design UI framework. Currently, I have a ...

Exploring the capabilities of useRef in executing a function on a dynamically created element within a React/Remix/Prisma environment

I've been trying to implement multiple useRef and useEffect instructions, but I'm facing difficulties in getting them to work together in this scenario. The code structure involves: Remix/React, fetching data from a database, displaying the data ...

Having trouble resolving bugs in a PHP script designed to update the status of 'open' or 'close' in a database

Seeking some assistance! :) Context of the issue: I manage an SQL database containing unique items with three columns: [index] [id] [status] [index] = incremented number [id] = unique string identifier [status] = '0' for open worksta ...

An action in redux-toolkit has detected the presence of a non-serializable value

When I download a file, I store it in the payload of the action in the store as a File type. This file will then undergo verification in the saga. const form = new FormData(); if (privateKey && privateKey instanceof Blob) { const blob = new Blo ...

Using Node.js to Send Emails via API

I've been grappling with an issue for over a week while trying to develop a web application that sends welcome emails to new subscribers. Despite my API code working perfectly, I cannot seem to get any output on the console indicating success or failu ...

When you click on a main category, a list of its corresponding subcategories will

concept image My vision involves having users click on a category from the top menu to display all main cards (parent cards), and then further clicking on a parent card will unveil its corresponding child cards. I've even included an image to help v ...

What is preventing the data property from updating in setInterval?

Looking for a way to increase the speed of the props while my marker is moving? Currently, the speed only updates when the pause button is clicked. How can I automatically update this.speed when clicking the speed button? I have defined the speed prop in ...

Is it necessary to utilize body-parser in our code?

In my research, I've noticed that many tutorials recommend using both express.json and bodyParser.json middleware. But aren't they essentially performing the same function? ...

Generating emails for error notifications with PHP and AJAX

I need assistance in sending an email using ajax and php <script type="text/javascript"> $(function() { $("#recibir").click(function() { var data = { email: $("#email").val(), ...

How to store data in MongoDB without relying on specific request bodies

I realize that I can simplify the code: var event = new EventModel(req.body); event.save....... If the input names match the attribute names in my database, mongoose can save by simply passing req.body. However, there is an issue with handling dateO sep ...

Dynamically load images from a database using PHP within a JavaScript AJAX script to display them in a jCarousel

I am encountering some challenges with dynamically loading images into my jCarousel AJAX gallery using PHP. I am unsure of how to integrate PHP code within the JavaScript code, especially when it comes to accessing data from a database. var mycarousel_ite ...

communicating data within a JavaScript file across server and client

One of my files, parameters.js, contains the following JavaScript code: const myJSON = { parameter1: 2, parameter2: 2. } module.exports = {myJSON} In another file called server.js, I can access this data by usin ...

Utilize JavaScript to assign a value to a concealed Pardot field

Recently, I've been working on setting a hidden Pardot field within an iframe. Oddly enough, when I manually input the query selector in my Chrome console, I successfully locate the element. However, when running this code snippet (embedded in the &l ...

Steps for clearing a set of checkboxes when a different checkbox is selected

While working on a website I'm developing, I encountered an issue with the search function I created. The search function includes a list of categories that users can select or deselect to filter items. This feature is very similar to how Coursera has ...

What is the best way to display input fields only if the previous input has a valid value?

My challenge involves creating a form with 3 to 10 text input fields. Initially, the form will display only 3 inputs (minimum). I am looking for an efficient way to dynamically show additional input rows as each previous row is filled out with a valid val ...

"Troubleshooting issues with retrieving data from database using Ajax and

Help needed! I'm facing issues with a select code while using ajax. The codes seem to be incorrect and not working as intended. Here is the snippet of the problematic code: <?php require_once 'config/dbconfig.php'; if (isset($_REQUE ...

Verify the Absence of an Internet Connection Through a Popup on a Windows 10 Application Developed in Javascript

Hey there, I've been browsing the web but can't seem to find a comprehensive tutorial on how to write a code that displays an error message when there is no internet connection. I'm currently using Visual Studio to develop a Windows 10 App w ...

I'm looking for recommendations on database management systems that are compatible with Node.js. Can

Could you recommend a reliable database that is compatible with node.js? I am currently using node webkit and need a robust DBMS for the backend. Any suggestions on plugins that may have external dependencies would be greatly appreciated. ...

Is there a way to eliminate a wrapper object from each element in a JSON array using JavaScript?

My knowledge of JavaScript is limited and I am facing a particular issue. The JSON document at hand looks like this: { "forecast": [ { "day-1": { "forecast_date": "2017-11-23", "morning": { "weather": { " ...

Is it possible to dynamically create and add new partitions to an existing topic in Node.js?

I am currently utilizing the "kafka-node" module to communicate with a kafka server, but I am unable to determine how to increase the number of partitions in an existing topic. For instance, I need to modify it from 4 partitions to 5. ...