I am having a problems in uploading an image from a modal form, after I click the upload button the modal form closes and I don’t know what happen because the modal closes and in my folder I am expecting an uploaded file but there is non. I am expecting to happen is that after I click the upload button it will automatically display the uploaded image in the modal form, Is my code missing something or what?
Here’s the jquery code I use:
$(function() {
$('button').button();
$('.upload-profile-pic').click(function() {
$.ajax({
url: 'upload-image.php',
method: 'post',
data: { uploadedfile: $('.profile-pic-name').val().trim() },
success: function(data) {
$('.new-profile-pic').html(data);
}
});
})
$('.update-profile-pic').click(function() {
$('#dialog').dialog({
width:350,
modal:true
});
});
});
Here’s my html form
<button class="update-profile-pic">Update Profile Picture</button>
<div id="dialog">
<p class="new-profile-pic">
</p>
<form enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
<input class="profile-pic-name" name="uploadedfile" type="file">
<input class="upload-profile-pic" type="submit" name="upload" value="Upload File">
</form>
<div>
And here’s my PHP code:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo '<img alt="" src="'.$target_path.'">';
} else{
echo "There was an error uploading the file, please try again!";
}
?>
You cannot do simple form uploads via ajax submits. You would have to use something like jquery form submit
usage:
You can refer to this example for further customization/changes