Quantcast
Channel: web development tutorials » ajax
Viewing all articles
Browse latest Browse all 7

Uploading files with Ajax using FormData Objects

$
0
0

HTML5 has One of the enhancements to XMLHttpRequest is the introduction of the FormData object. With the FormData object, you can create and send a set of key/value pairs and, optionally, files using XMLHttpRequest. When using this technique, the data is sent in the same format as if you’d submitted it via the form’s submit() method with the encoding type of multipart/form-data.

FormData gives us a way to create HTML forms on-the-fly using JavaScript, and then submit them using XMLHttpRequest.send()

Example:

var formData = new FormData();
formData.append("username", "maheshchari"); 
formData.append("password", 'password');
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/register");  
xhr.send(formData);

We can make changes to existing formdata before submitting with Ajax

var formElement = document.getElementById("formId");
var formData = new FormData(formElement);
formData.append("additional_data", "some secrete");
 
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/");
xhr.send(formData);

Processing form data with jQuery

var fd = new FormData(document.getElementById("formId"));
fd.append("CustomField", "This is some extra data");
$.ajax({
  url: "post.php",
  type: "POST",
  data: fd,
  processData: false,  // tell jQuery not to process the data
  contentType: false   // tell jQuery not to set contentType
});

sending files

var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST",uploadURL);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");	
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        $('#output').html(xhr.responseText);
    }
}
xhr.send(formData);

Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles



Latest Images