Submitting a Form using AJAX in vanilla JavaScript (without the use of jQuery)

I'm looking for guidance on how to send a Form via an AJAX request. Specifically, I need help with the 'xmlhttp.open' line. The goal is to upload a video file to a third party video hosting site using their API and provided URL ('upload_link_secure'). Can anyone provide assistance?

Here's my HTML:

<form id="upload" action="'+upload_link_secure+'" method="PUT" enctype="multipart/form-data">
  <input type="file" id="vidInput">
  <button type="submit" id="submitFile" onclick="uploadMyVid(\''+upload_link_secure+'\')">Upload Video</button>
</form> 

This is my javascript:

 var uploadMyVid = function(upload_link_secure){

        var form = document.getElementById('upload')

        // FETCH FILEIST OBJECTS
        var vidFile = document.getElementById('vidInput').files;

        var xmlhttp = new XMLHttpRequest;

        xmlhttp.open('PUT', );  // Need help completing this line???
        xmlhttp.send(vidFile);

    }

Answer №1

Before anything else, make sure to correct the action attribute by changing it to a valid endpoint such as /upload.

Below is an example that demonstrates how to upload without server-side processing:

var form = document.getElementById("upload-form"),
        actionPath = "";
        formData = null;

    var xhr = new XMLHttpRequest();

    form.addEventListener("submit", (e) => {
        e.preventDefault();
        
        formData = new FormData(form);
        actionPath = form.getAttribute("action");

        xhr.open("POST", actionPath);
        xhr.send(formData);

    }, false);
<form id="upload-form" action="/upload" method="POST" enctype="multipart/form-data">
      <input type="file" id="file">
      <button type="submit">Upload Video</button>
</form>

Answer №2

Swap out the <button> element for a <span> element and add a click event handler to the #submitFile element. Use FormData() with XMLHttpRequest() to transmit the File object from the <input type="file"> .files object. Eliminate the action attribute in the <form> element, and specify the URL for the PUT request in XMLHttpRequest.prototype.open().

<body>
  <form id="upload">
    <input type="file" id="vidInput">
    <span id="submitFile" 
      style="-webkit-appearance:button;-moz-appearance:button;padding:4px;font-family:arial;font-size:12px">Upload Video</span>
  </form>
  <script>
    function uploadMyVid(event) {

      // ACCESS FILE OBJECTS
      var vidFile = document.getElementById('vidInput').files;

      var xmlhttp = new XMLHttpRequest;

      xmlhttp.open('PUT', "secure_upload_link");

      var data = new FormData();
      data.append("file", vidFile[0], vidFile[0].name);

      xmlhttp.send(data);

    }

    var button = document.getElementById("submitFile");
    button.addEventListener("click", uploadMyVid);
  </script>
</body>

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

JavaScript animation not functioning properly when height is set to "auto"

Can someone help me figure out why setting the height to "auto" in the code snippet below isn't working as expected? I want the DIV to adjust its size based on the content, but it's not happening. Any ideas on how to fix this issue would be great ...

What is the best way to locate the key with the greatest value in an array that is less than or equal to a certain

In my data structure, I have an array that maps user levels to the minimum points required for each level. Here's how it looks: $userLevels = array(0 => 0, 1 => 400, 2 => 800); The keys represent user levels and the values represent the min ...

Remove the session variable when a JavaScript function is triggered

After creating a function called destroy(), I have set it to be called on the onclick event of the logout button. However, the issue is that the server-side code within that function is always executed when the page loads, regardless of whether the logou ...

Web audio: setTimeout slows down when mobile screen is turned off

In response to Yogi's feedback (refer to the discussion on "setTimeout" and "throttling" in https://developer.mozilla.org/en-US/docs/Web/API/setTimeout ), I attempted to enhance performance by integrating an AudioContext. document.addEventListener(&ap ...

Issue with Github actions: Failure in mark-compacts process due to ineffective operation near heap limit causing allocation failure - running out of memory in

Whenever I try to build my library files, I keep encountering an out of memory error. In my local setup, I was able to resolve this problem by executing the command export NODE_OPTIONS="--max-old-space-size=8192". Unfortunately, no matter how mu ...

Efficiently making JQuery Ajax requests using HTTP Basic Authentication

I am currently experiencing challenges with implementing HTTP Basic Authentication in JQuery when communicating with a REST-based server. This server provides responses in both XML and JSON formats, but I have chosen to work with JSON format. Our authoriz ...

Tips for setting multiple states simultaneously using the useState hook

Exploring the use of multiple states handled simultaneously with the useState hook, let's consider an example where text updates based on user input: const {useState} = React; const Example = ({title}) => { const initialState = { name: &a ...

Utilizing Redux state data in a hyperlink: A step-by-step guide

I am a beginner in Redux and ReactJS. I'm working on using a state data called type within the link retrieved via Axios on line 17. The value of type is set from another .jsx file using dispatch(). In this Home.jsx file, dispatch is called on line 24 ...

Enter the text value into the input field using live search through AJAX

I stumbled upon this AJAX Live Search PHP script that functions perfectly. Here is the Live Preview. However, instead of opening a new window when clicked, I want the text of the clicked element to be placed in the search box. After modifying the search.ph ...

The fitBounds and panToBounds functions in react-google-maps fail to properly adjust the map's size

const Map = withGoogleMap(props => { const { activeMarker, zoom, center, showInfoWindow, products } = props; const [selectedPlace, setSelectedPlace] = useState(null); // Code to iterate through items and adjust map size, center, and zoom to inclu ...

A guide to delivering static images using NestJS

I recently started learning the MEAN stack and while exploring Express, I came across an additional layer in the framework called NestJS. It had everything I needed and the Angular-like syntax was perfect for me. However, each new step has been a nightmar ...

Validating input using jQuery Validate and implementing cross-domain remote validation with JSONP

Having an issue with jQuery Validate and cross domain remote validation in a unique scenario: PhoneGap mobile app PHP scripts on remote server jQuery 1.9.1 jQuery Mobile 1.4.2 for interface framework Using jQuery Validate 1.12.0 for forms validation plug ...

most efficient method of sharing information between various angular controllers

I am looking for a way to share form data among multiple controllers before submitting it. Currently, I am using module.value() to store the data as a global variable. var serviceApp = angular.module('sampleservice', [ ]); serviceApp.valu ...

Angular Search Version 2.0

I am facing an issue with my search functionality in Angular 2. When I type into the search box, the search method on the service is not triggered. I believe there might be a simple solution that I am missing. Any assistance would be greatly appreciated. ...

An issue occurred while trying to retrieve the js file, as an error with code net::ERR_ABORTED 404 (Not

Although this question has been asked before, I am unsure where to find the solution. My express backend server needs to render an HTML page with main.js in it upon launch. app.js code: var createError = require('http-errors'); var express = req ...

To access ES Module, importing is necessary

I'm currently working on a project to develop a service that can convert SVG files into PNG format using the svg2img package. Everything is running smoothly when testing locally with vercel dev, but I keep encountering an error whenever I try to deplo ...

Is it possible to declare variables using the "this" keyword?

Consider the scenario where this.x=5 is declared and assess the accessibility of all relevant places. <script> $(document).ready(function(){ $("button").click(function(){ this.x=!this.x; $("#div1").fadeTo(400,this.x ? 0.4 : 1); }); }); & ...

Setting up AntiXSS with .Net 3.5: A comprehensive guide

Hello, I am currently using the Ajax HtmlEditorExtender on one of my TextBoxes. It has been highly recommended to implement the AntiXSS Sanitizer for security purposes. Here is the configuration I added in my web.config file: <configSections> <se ...

Tips for placing a marker at the center of the screen on Google Maps

I am developing a transportation app similar to Uber or Lyft using JavaScript. I am looking to retrieve the map location with the center of the screen, where there is a marker located at y = 0 and x = 0. Similar to the image below: The user should be abl ...

Tips for adjusting border colors based on the current time

Trying to change the border color based on the opening hours. For example, green border from 10am to 9:29pm, yellow from 9:30pm to 9:44pm, and orange from 9:45pm until closing at 10pm. The issue is that the colors change at incorrect times beyond midnight. ...