Ajax requests with file support

// Vanilla Javascript var form = document.querySelector('form'); form.addEventListener('submit', function(e) { e.preventDefault(); var request = new XMLHttpRequest(); request.open('POST', 'http://somewhere.com', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.send(new FormData(e.target)); }); // jQuery $('form').on('submit', function(e) { e.preventDefault(); $.ajax({ url: 'http://somewhere.com', type: 'POST', data: new FormData(e.target), processData: false, contentType: 'application/x-www-form-urlencoded; charset=UTF-8' }); }); // Angular 1.* // Inside a controller vm = this; vm.submit = function($event) { $event.preventDefault(); $http.post('http://somewhere.com', vm.user, { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, transformRequest: function(data) { if (undefined === data) return data; var formData = new FormData(); angular.forEach(data, function(value, key) { if (value instanceof FileList) { formData.append(key, value[0]); } else { formData.append(key, value); } }); return formData; } }); }
This snippets shows how to make an ajax request sending the content as FormData making possible include files in the payload.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.