Follow by Email

How to upload Image file using AJAX using jQuery in PHP

In PHP you can easily upload any type file on the server using the move_uploaded_file() method.

But it requires form submit for uploading the selected file.

If you want to store image file and display preview without reloading the whole page then you need to use jQuery AJAX.

Send the selected file using the FormData object in the AJAX request.

Steps:

  1. First You need to Select image file through following line of html code
input type="file" id="image_to_upload"

2. After that you need to write the following jQuery code to catch this event.

jQuery.noConflict();    
formdata = new FormData();
jQuery("#image_to_upload").on("change", function() {
var file = this.files[0];
if (formdata) {
formdata.append("image", file);
jQuery.ajax({
url: "destination_ajax_file.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success:function(){}
});
}
});

3. In the destination ajax file you can access image by the following variable

print_r($_FILES);

Conclusion

Use FormData object to store the file and pass in the AJAX request to upload it.

In the PHP file access the file using $_FILES.



How to upload Image file using AJAX using jQuery in PHP How to upload Image file using AJAX using jQuery in PHP Reviewed by RS Coder on June 18, 2020 Rating: 5

No comments:

Disqus Shortname

banner image
Powered by Blogger.