Sometime you need to upload the image without refreshing the page , in that case you can upload the image with the help of ajx using FormData Objects .
To achieve this lets create a form in HTML to upload the file.
<div class="controls">
<input id="fileInput" name="image-file" type="file">
</div>
Now come to the javascript part where we will upload the image using ajax :-
$("input[name='image-file']").on("change", function() {
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return;
if (/^image/.test(files[0].type)) {
var reader = new FileReader();
reader.readAsDataURL(files[0]);
var fd = new FormData();
fd.append('addImage', files[0]);
reader.onloadend = function() {
$.ajax({
url: 'upload.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data) {
console.log('image uploaded');
}
});
}
}
});
In above javascript code we have send the image data when someone upload the image,
Now lets write the php code in upload.php file.
move_uploaded_file($_FILES["addImage"]["tmp_name"], "images");
0 Comment(s)