Download ajax jquery image

Im new for jQuery. I am trying to upload a jpg image file using ajax method. But when I load, it does not load. Can someone help me do this?

HTML

<form action="" method="POST" enctype="multipart/form-data"> <input type="file" name="image" id="image"/> </form> 

JQuery

 $('#submit').click(function() { var image=$('#image').val() $.post("upload.php",{image:image},function(data) { alert(data); }); } }) 

Php

 <?php $image=$_POST['image']; $imagename=date("dmY")."-".time()."jpg"; $target_path = "uploads/".$imagename; if(move_uploaded_file($image, $target_path)) { echo 'moved'; } else { echo 'error'; } ?> 
+2
source share
1 answer

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'; } ?> 
+3
source

All Articles