To upload a file using ajax , you need to use FormData as shown below.
$("form").on('submit', (function(e) { e.preventDefault; var formData = new FormData(this); $.ajax({ url : "upload.php", type : "POST", data : formData, cache : false, contentType : false, processType : false, success : function(data) { alert(data); } }); }));
And your PHP script should look like this.
<?php $image=$_FILES['image']; $image_tmp =$_FILES['image']['tmp_name']; $imagename=date("dmY")."-".time().".jpg"; $target_path = "uploads/".$imagename; if(move_uploaded_file($image_tmp, $target_path)) { echo 'moved'; } else { echo 'error'; } ?>
source share