Trigger form submission upon file upload via ajax

I am struggling with submitting a form to upload a file using AJAX. My main issue is sending the temporary path to PHP and then receiving an array as a response.

Essentially, my goal is to submit the form, retrieve the temp path, pass it to PHP through JS, and finally have PHP return an array in response to JS

This is the current code I have developed:

<form name="form1" id="frmXML" method="post" action="">
<div>
    <label for='upload'>Add XML:</label>
    <input id='upload' name="upload[]" type="file" accept=".xml" multiple="multiple" onchange="doSelect(this)"/>
</div>

JS:

function doSelect(el){

    $.ajax({
        type : 'POST',
        data: {
                path:this.document.getElementById('upload').value,
                submit: 'submit',
              }
        url : 'Logic/User.php',
        dataType:'json',
        success : function(response){

            var len =response.length;

            if(len>0)
            {
                //Do something              
            }
        }
    });
    return false;

  }

Answer №1

It is not possible to achieve this.

Setting aside the complexities of combining Ajax and non-Ajax operations, here's what would transpire:

  1. The form will send the file to PHP
  2. The PHP script will execute, allocate a temporary path for the file, create a response, remove the file from the temporary location, and terminate
  3. The JavaScript code will receive an invalid file path
  4. The JavaScript will try to initiate an Ajax request to another PHP endpoint with the incorrect file path
  5. The other PHP script will be unable to locate the file linked to that path since it has already been deleted

If you intend to utilize Ajax while handling files, the simplest method would be to make a single HTTP request through Ajax and include the file within it.

Answer №2

My understanding is that you are looking to automatically submit the form once the ajax request has finished. In that case, this code snippet should meet your needs:

if(len>0)
    {
        $('form').submit()              
    }

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

Tips for concealing a Div in an HTML document with the help of Angular

I need a solution to hide a div that contains only titles, while the div with the actual content is located in a different section <div> <b>Delivery Info\</b> <div class="custom-control">Delivery ID: </div ...

Sort the array in alphabetical and numerical order while meeting a specific condition

In my code, I am attempting to sort an array based on two conditions. Specifically, I need to ensure that Pos 10 comes after single digits and follows a specific order after that. Initially, I tried to prioritize strings containing the word first, but whe ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

Sharing Data Across Multiple Windows in Angular 2 Using a Singleton List

My multiplayer game involves adding new players to a single game room lobby, which is essentially a list of current players. How can I update this list for all connected players when new ones join? I implemented a service and included it in the providers ...

How come CSS styles are not being applied to forms in AngularJS?

When attempting to apply CSS styles to a form in order to indicate invalid input, I encountered an issue. Even after using the important tag, the styles did not change. I created a dynamic form from JSON and now need to validate it. Following a suggestion ...

What is the best way to utilize jQuery to send JSON data and then parse it on a subsequent HTML page via the

My goal is to send JSON data through the URL to the next HTML page. While testing it on an emulator for a mobile app, I encountered an issue where the URL crashed instead of redirecting to the next page. Can someone help me understand why this might be hap ...

Activate button on ASP.NET once HttpResponse is received

After clicking a button on my ASP.NET page, it gets disabled to prevent double clicking and triggers the following function: Private Sub ExportToExcel(ByVal nameReport As String, ByVal wControl As GridView, ByVal sTitle As String) Dim responsePage As H ...

Attempting to retrieve an object's attribute

Hey! I have a question regarding the screenshot in this link: I'm trying to access the user object with the property team. So far, I've attempted using data.Object, but it returns an undefined output. I also tried using data.user but that resul ...

React Native's 'onMessage' feature is currently experiencing issues and is not functioning

I'm attempting to retrieve the content of a URL by sending a post message and then listening for it using onMessage, but unfortunately it does not seem to be functioning properly. render(){ const getHtmlJS = "window.postMessage(document.getElementsBy ...

Steps to link two mat-autocomplete components based on the input change of one another

After reviewing the content on the official document at https://material.angular.io/components/autocomplete/examples I have implemented Autocomplete in my code based on the example provided. However, I need additional functionality beyond simple integrati ...

What is the best method for importing and utilizing child components exclusively?

Consider the following example with different components: first.js <div> <Route path='/' /> <Route path='/first' /> </div> second.js <div> <Route path='/second' /> <Redi ...

How can I manage file input within a Vue.js application?

After attempting to open a file input with a button, I encountered an issue. When clicking the button, the client reported: “this.$refs.image.click”. Below is my code snippet: <v-btn height="50" ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

Enable or disable options with the user's permission

Currently, I am developing a WordPress plugin that will display a simple div on all pages. The code is set up to create the div, turn it into a shortcode, and then show it on each page. I want to include a checkbox in the admin settings so that users can ...

Leverage jQuery to organize and categorize JSON information received through an Ajax call

I have retrieved the following array from a MySQL database using PDO: [{ "tbl":"1", "orid":"915", "date":"2021-12-30 12:46:48", "flag":0 }, { "tbl":"2", "orid":"914", "date":"2021-12-30 12:46:21", "flag ...

Submitting a file to the Slack API via the files.upload method using jQuery

I'm attempting to upload a file on a webpage and send it to Slack using the Slack API. Initially, my code looked like this: var request = require('request'); $(".submit").click(function(){ request.post({ url: 'https://slack.co ...

JavaScript Switch Open/Close Mobile Navigation Menu

I'm currently facing a challenge with a specific issue. I want to implement a toggle menu for mobile devices on a website that I'm developing. It's functioning smoothly, and you can see it in action on this CodePen. The JavaScript code for ...

Retrieving unprocessed HTTP response using AJAX

Is it possible to retrieve the full raw HTTP response from the server using plain JavaScript AJAX in a web browser? When I say raw response, I mean both headers and body in a raw text format like the following: < HTTP/1.1 301 Moved Permanently < Lo ...

Having difficulty converting an object into an iterable using an arrow function

Currently immersed in learning JavaScript, I successfully created a class and now find myself faced with the task of making it iterable. The Group class represents a collection of values, akin to a Set, equipped with methods for adding, removing, and che ...

struggling to incorporate API Json response data into my HTML file using AngularJS

Below is the code I am currently using: angular.module('ngApp', []) .factory('authInterceptor', authInterceptor) .constant('API', 'http://myserver.com/app/api') .controller('task', taskData) function task ...