Explain Codes LogoExplain Codes Logo

How to send FormData objects with Ajax-requests in jQuery?

javascript
ajax-requests
formdata
jquery
Nikita BarsukovbyNikita Barsukov·Feb 21, 2025
TLDR
$.ajax({ url: "submit.php", // Replace with your <insert fav sci-fi movie> spaceship coordinates type: "POST", data: new FormData($('form')[0]), // Grab form data as FormData object processData: false, // This ain't your grandma's recipe! No processing please! contentType: false, // Don't tell me what I am! Prevent setting content type success: function(response) { // Party callback when it all goes to plan console.log(response); // Peek into the Pandora's box of server response } });

This is how you send a form as FormData using jQuery's $.ajax directive, with processData and contentType set to false to enable multipart encoding.

Life-changing FormData hacks

FormData and Ajax are BFFs (best friends forever — discuss!).

  • Appending extra data: FormData holds values like a pro. Here's how it's done:

    let formData = new FormData(); formData.append('username', 'johndoe'); // Prepping username for the journey formData.append('profile_picture', $('input[type=file]')[0].files[0]); // That dazzling smile will blind the server for sure
  • Handling of files: To upload files, you need to treat the file input with the respect it deserves:

    formData.append('file', $('input[type=file]')[0].files[0]); // Send the pic of your beloved pet or the doc you spent nights working on
  • Non-JSON Responses: The server talks more than just JSON, so set dataType as needed.

Bulletproof ajax and FormData setup

They say the road to Hell is paved with the default Ajax request configuration, so here are some holy safeguards:

  • Optimizing HTTP requests: cache: false. Browser cache is for quitters. Live dangerously.
  • Customizing with beforeSend: Tune the jqXHR object with beforeSend. Bring your mad scientist goggles!
  • DOM readiness: Wrap your code in $(document).ready(). Less haste, more speed.

Advanced tricks for FormData and Ajax

Let's roll up our sleeves, dive in and get our hands dirty:

  • Setting enctype: When blasting a file across the web, set the form's enctype to 'multipart/form-data' for a smooth sail.
  • Unique file naming: Clash of the files? Evade it by assigning unique filenames using the server's handy-dandy time() function.
  • Correct PHP file handling: Use move_uploaded_file() to escort the files to their new homes.

Tic Tac Toe with Ajax

Sometimes, you just need Ajax to respond to your events like ringing a bell for the butler:

$('#uploadButton').on('click', function() { // Swoosh! Off goes the AJAX request });

Overcoming hurdles with uploaded files

Naming conflicts are like Kardashians, everyone loves to hate 'em. Here's how you can avoid them:

$uniqueName = time() . '_' . $_FILES['file']['name']; // It's like taking attendance in a class. move_uploaded_file($_FILES['file']['tmp_name'], "uploads/" . $uniqueName); // School's out! Off to their new seats.