Example 1: ajax file upload jquery
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response);
}
});
});
Example 2: file upload in php through ajax
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
Example 3: file upload in php through ajax
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Example 4: Upload image via ajax (jquery)
var form = new FormData();
form.append('varName','data');
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
},
error: function(data){
}
});
Example 5: upload form with doc type in ajax
$(".submitbtn").on("click", function(e) {
var form = $("#Form");
var formData = new FormData(form[0]);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: $(form).prop("action"),
data: formData,
contentType: false,
processData: false,
error : ErrorHandler,
success : successHandler
});
}
});