Using Ajax Uploader multiple times in a single page

I created a custom ajax file uploader that functions perfectly with one instance on the page. However, I am currently facing an issue while trying to modify it to support multiple instances. When I attempt to upload multiple files using one form, the first file uploads successfully. But for all subsequent files, it redirects to the next file in line from the second form instance. Strangely, if I upload using the last (second) instance of the form, multiple files upload without any problems. The unique ID names are used consistently throughout the upload form and referenced in the JavaScript functions. Below are snippets of the relevant code:

The forms are dynamically generated by PHP with a randomly generated unique ID $uid. First, the initialization of the upload function is output to the page within a <script> tag:

'<script> '.
    'jQuery(document).ready(function($){ '.
        'var myup_'.$uid.' = new MyUp({ '.
            // other settings being passed
        }); '.
    '}); '.
'</script>';

Similarly, the HTML form snippet includes the necessary input fields:

'<div class="myup_container" style="'.$inlinestyle.'">'.
    '<form name="myup_form_'.$uid.'" id="myup_form_'.$uid.'" action="javascript:void(0);" enctype="multipart/form-data">'.
        // more form elements
    '</form>'.
    // additional div elements as needed
'</div>';
More details can be found in the complete JavaScript segment posted above. If there's a straightforward solution to resolve this issue with multiple instances interfering with each other during file uploads, kindly provide your insights.

Answer №1

The constructor function in the provided code snippet declares all prototype methods, leading to them being overridden every time a new MyUp object is created. As a result, each object will use the configuration from the most recent one.

function MyUp(config) {
    /// ...
    var self = this;
    MyUp.prototype.foo = function() {
        // utilize `self`
    };
}

To avoid this issue, it is recommended to define the methods only once and reference the this keyword within the functions:

function MyUp(config) {
    /// ...
}
MyUp.prototype.foo = function() {
    // utilize `this`
};

If there is a need for static members within the class (methods or variables that are not associated with any instance), they can be declared as properties of the function. For public usage - MyUp.begin = function() {}. Alternatively, for private usage, these static members can be defined inside a module:

(function() {
   var uploadsInProgress = 0;

   // declare MyUp and incorporate uploadsInProgress; hidden from external code

   window.MyUp = MyUp;
})();

This approach may not completely resolve the upload issues, but it certainly aids in maintaining clarity when creating multiple objects.

Answer №2

After struggling to implement Alex Gyoshev's suggestion (due to my own shortcomings), I ultimately decided to completely abandon the object/prototype approach. Instead of instantiating objects within the form, I opted to declare a MyUpConfig variable as an empty array in the global scope. For each html form, I appended MyUpConfig['.$uid.'] = followed by an array of settings.

In the javascript file, I associated each form's file input and submit events with its unique id, storing the file data for each input field in an array: TheFiles[uid] = files. This way, during the upload submit process, it retrieves the uid from the upload button element and only uploads files corresponding to that specific id in the array.

I successfully implemented multiple upload forms on a single page, allowing them to operate simultaneously without any interference.

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

What's the reason why Angular stops flickering with the use of "/" in href?

Recently, I've come across a peculiar issue in one of my web applications while using Angular's routeProvider as a template engine. The app functions properly, but the behavior seems inexplicable to me. The problem arises during page transitions ...

How do I make an AJAX request in Rails without including a question mark in the data?

Currently, I'm attempting to make a GET request to my /routes/ controller in order to retrieve some data. Here is the code snippet I have so far: function fetchMarker(id) { var data; $.ajax({ type: "GET", url: '/routes/&a ...

Error loading content for webpack://SwaggerUIBundle/src/core/system.js in Swagger UI

When trying to utilize Swagger UI for documenting a Laravel project using the URL http://localhost:8014/api/documentation, I came across an error displayed in the browser console: Error: Unable to destructure property 'type' of 'u' as i ...

What is the best way to extract row data from a datatable and transmit it in JSON format?

I have successfully created a code that retrieves data from a dynamic table using ajax. However, I am facing an issue where I only want to send data from checked rows. Despite trying different approaches, I keep encountering errors or receive an empty arra ...

The Custom Validator encounters an issue retrieving the Combobox identification

I have encountered an issue where the Required Field validator fails for the Ajax Combobox, so I decided to use a custom Validator instead. However, I am facing difficulties in getting it to work with the Combobox. Interestingly, when I pass the Id of anot ...

Discover the power and potential of Ajax in combination with PHP and

Here is my AJAX code snippet: jQuery(document).ready(function($) { $(".respond").submit(function(event){ ..................//something here request = $.ajax({ url: "/admin/check.php", type: "post", data: {formData:serialized ...

The Angular controller failed to return a defined value

I recently took over a legacy VB.Net application and noticed that both the ng-app and ng-controller directives are present on the HTML element in the root master page: <html runat="server" id="html" ng-controller="MasterController"> The ng-app attr ...

Reasons Child Components in React Native & Redux Are Not Re-rendered with Every State Update

Within my React Native and Redux setup, I have a <NavigationCardStack/> component serving as the root. Whenever the state is updated, the redux-logger correctly displays the new state. However, after a state change, the child component fails to log ...

Angular repeatedly executes the controller multiple times

I have been working on developing a chat web app that functions as a single page application. To achieve this, I have integrated Angular Router for routing purposes and socket-io for message transmission from client to server. The navigation between routes ...

What are the implications of AngularJS's filter on performance?

I came across an interesting article on optimizing ng-repeat in AngularJS that discussed the following: An AngularJS filter in your HTML will run multiple times during every digest cycle, even if there have been no changes in the data or conditions. Thi ...

Tips for temporarily halting my animation using javascript

I'm working on animating a background image and I'd like to implement a pause feature within this function. Do you have any suggestions for the best practice to do this? function scrollBg(){ //Move to the next pixel row. current -= step; ...

The radio button fails to trigger the setState function in React

In my React program, I have implemented a method to update the state and modify a specific value for a Radio button: The state : class App extends Component { constructor(props) { super(props); this.state = { checked: [], expanded: [], ...

extracting the data from the list item within an AJAX response

Attempting to create a search function that retrieves the value inside an li element from an AJAX response. Here is my HTML page: <form role="form" action="<?php echo base_url();?>comparison/selCourse" method="post" id="selAll"> <h4> ...

`Incompatibility with Internet Explorer causes AJAX loader GIF to fail when using asynchronous POST requests`

Is there a way to display an AJAX loader gif during an asynchronous POST request on Internet Explorer? It seems that the request process stalls and the updated content is not visible when using Internet Explorer. However, everything works fine on browser ...

What steps do I need to take to ensure a prepared statement update functions properly in Node.js using JavaScript?

.then(function (val) { var roleIdentity = roleArr.indexOf(val.role) + 1; db.query( 'UPDATE employee SET role_id = ? WHERE first_name = ? AND last_name = ?;', [roleIdentity, val.firstname, val.lastName], functio ...

Encountering an issue with a React-slick slider test case - receiving an error related to the inability to access property 'querySelector

I am currently utilizing next.js for a React project and have incorporated the react-slick slider plugin successfully. However, I encountered an issue when attempting to run tests as it displayed a `TypeError: Cannot read property 'querySelectorAll&ap ...

Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning. Below is the code I am currently using: <style> #map-london { width: 500px; height: 400px; } #map-belgium { wi ...

Tips for resolving the DOMException error "Failed to execute 'open' on 'XMLHttpRequest': Invalid URL in a MERN Stack application"

Hey there, I encountered an error after deploying my app on Heroku. The frontend seems to be working fine but I suspect there's a problem with the backend. DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL a ...

Managing input/output requests on Amazon EC2 instances

Having mastered node, javascript, and other technologies the hard way, I am finally on the brink of releasing my debut web application. After signing up for Amazon Web Services and setting up a micro instance to take advantage of the first year's free ...

Using JQuery to attach an event listener to Ajax success

What is the purpose of using bind on AJAX success calls? Consider the following code snippet: $.ajax({ url: myurl, dataType: 'json', success: function(data){ this.setState({data: data}); }.bind(this) }); Is there any dif ...