Table of Contents
1. Before introducing the use of FormData to make Ajax requests and upload files, let’s first get to know FormData and its use:::::" >1. Before introducing the use of FormData to make Ajax requests and upload files, let’s first get to know FormData and its use:::::
2. Use the FormData object to send binary files:::::" >2. Use the FormData object to send binary files:::::
3. Example " >3. Example
4. Browser compatibility" >4. Browser compatibility
Home Backend Development PHP Tutorial FormData object makes Ajax request and uploads files

FormData object makes Ajax request and uploads files

Jul 18, 2018 pm 04:20 PM

This article shares with you the method of making Ajax requests and uploading files using the FormData object. Friends in need can refer to it.

XMLHttpRequest Level2 adds a new interface - FormData. [ is mainly used to send form data, but can also be used independently to transmit keyed data. Compared with ordinary Ajax, it can upload binary files asynchronously

Using the FormData object, you can use some key-value pairs to simulate a series of form controls through js, and you can also Submit the form asynchronously using the send() method of XMLHttpRequest.

First of all, in the previous "Parameter Passing Method for Front-end and Back-end Interaction", we talked about the traditional form submission method (form serialization), which is only suitable for passing general parameters. The file stream of the uploaded file cannot be serialized and delivered. Therefore, using FormData, you can easily combine it with ajax to upload files.

1. Before introducing the use of FormData to make Ajax requests and upload files, let’s first get to know FormData and its use:::::

W3C draft provides three options to obtain or modify Form Data:::

WAY1: Create an empty Form Data object, and then use append() to add it one by one Key-value pair

var oMyForm = new FormData();    // 创建一个空的FormData对象
oMyForm.append("userName","Coco");       // append()方法添加字段
oMyForm.append("accountNum",123456);   // 数字123456立即被转换成字符串“123456”
oMyForm.append("userFile",fileInputElement.files[0]);var oFileBody = "<a id="a"><b id="b">hey!</b></a>";
var oBlob = new Blob([oFileBody],{type:"text/html"});  // Blob对象包含的文件内容是oFileBody
oMyForm.append("webmasterfile",oBlob);
var oReq = new XMLHttpRequest();
oReq.open("POST","   .php");
oPeq.send(oMyForm);   // 使用XMLHttpRequest的send()把数据发送出去
Copy after login

The values ​​of "userFile" and "webmasterfile" above both contain a file; the

field The value can be a Blob object, File object or string. Other types will be automatically converted to strings - such as "accountNum" above.

WAY2: Take the form element object as a parameter and pass it into the FormData object

—— Pseudo code——

var new_FormData = new FormData( someFormElement );
Copy after login

Example:

var FormElement = document.getElementById("myFormElement");var oReq = new XMLHttpRequest();
oReq.open("POST","     .php");
oReq.send(new FormData(FormData));
Copy after login

You can also add new key-value pairs based on the existing form:

var FormElement = document.getElementById("myFormElement");var formData = new FormData(FormElement);
formData.append("serialnumber",serialNumber++);var oReq = new XMLHttpRequest();
oReq.send(formData);
Copy after login

You can add some fixed fields that you don’t want users to edit in this way before sending.

WAY3: Use the getFormData method of the form object to generate

var formobj = document.getElementById("myFormElement");
var formdata = formobj.getFormData();
Copy after login

Use the FormData object, combined with native js, through Ajax implements asynchronous uploading of images. Of course, the principle of existing jquery batch upload plug-ins is to use FormData.

2. Use the FormData object to send binary files:::::

way1: Initialize FormData through the form form

1. There is a form element containing a file input box in html

<form enctype="multipare/form-data" method="post" name="fileinfo">

      <label>your email address:</label>
      <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64"/><br>

      <label>custom file label:</label>
      <input type="text" name="filelabel"  size="12" maxlength="32"/><br>

      <label>File to stash:</label>
      <input type="file" name="file" required></form><p id="Output"></p><a href="javascript:sendForm()">stash the file !</a>
Copy after login

2. Asynchronously upload the file selected by the user

function sendForm(){      var oOutput = document.getElementById("Output");      
var oData = new FormData(document.forms.nameItem("fileInfo"));
      oData.append("customField","This is some extra data");      
      var oReq = new XMLHttpRequest();
      oReq.open("POST","     .php",true);
      oReq.onload = function(oEvent){            
      if(oReq.status == 200){
                   oOutput.innerHTML = "Uploaded!";
            }else{
                   oOutput.innerHTML = "Error" + oReq.status + "occurred uploading your file!"
            }
      };
      oReq.send(oData);
}
Copy after login

WAY2: Add a File object or a Blob object directly to the FormData object without using the form form

var data = new FormData();var oFileBody = "<a id="a"><b id="b">hey!</b></a>";var oBlob = new Blob([oFileBody],{type:"text/html"});

data.append("myfile",oBlob);
Copy after login

If a field value in the FormData object is a Blob object, when sending an HTTP request, the value of the "content-Disposition" request representing the file name of the file contained in the Blob object is different in different browsers:

Firefox uses the fixed string "blob", while chrome uses a random string.

WAY3: Use Jquery to send FormData (relevant items must be set correctly)

var fd =new FormData(document.getElementById("fileinfo"));
fd.append("customField","This is some extra data");
$.ajax({
     url:"    .php",
     type:"POST",
     data:fd,
     processData:false,   //  告诉jquery不要处理发送的数据
     contentType:false    // 告诉jquery不要设置content-Type请求头});
Copy after login

3. Example

1. Use FromData to make Ajax requests and upload files

<form id="uploadForm">
      指定文件名:<input type="text" name="filename" value="">
      上传文件:<input type="file" name="file">
      
       <input type="button" value="上传" onclick="doUpload()"></form>
Copy after login
function doUpload(){    var formData = new FormData($("#uploadForm")[0]);
    $.ajax({
          url:"   .php",
          type:"POST",
          data:formData,
          async:false,
          cache:false,
          contentType:false,
          processData:false,
          success:function(returndata){
                 alert(returndata);
          },
          error:function(returndata){
                 alert("error:"+returndata);
          }
    });
}
Copy after login

2. Use FormData to submit forms and upload images

<form name="form" id="formData">

       name:<input type="text" name="name">
       gender:<input type="radio" name="gender" value="1"> male              
       <input type="radio" name="gender" value="2"> female
       photo:<input type="file" name="photo" id="photo">

       <input type="button" name="btn" value="submit" onclick="submit();">       
       </form><p id="result"></p>
Copy after login
function submit(){       
var data = new FormData($("#formData")[0]);
       $.ajax({
              url:"    .php",
              type:"POST",
              data:data,
              dataType:"JSON",
              cache:false,
              processData:false,
              contentType:false
        }).done(function(ret){                  
        if(ret["isSuccess"]){                      
        var result = "";
                      result +="name=" + ret["name"] + "<br>";
                      result += "gender=" + ret["gender"] + "<br>";
                      result += "<img src=&#39;"+ret[&#39;photo&#39;]+"&#39;width=&#39;100&#39;>";
                             
                      $("#result").html(result);         // 提交成功后将表单数据显示在id="result"的p里面     
                  }else{
                         alert("提交失败");
                   }
         });       return false;
}
Copy after login

4. Browser compatibility

Chrome Firefox(Gecko) IE Opera Safari
7 4.0(2.0) 10 12 5

Related recommendations:

jQuery uses FormData to implement file uploading

Use FormData to upload files with Ajax

The above is the detailed content of FormData object makes Ajax request and uploads files. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles