I have a simple upload image form...
<form id="form" action="upload-image-ajax.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
And some JS...
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload-image-ajax.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if(data=='invalid file') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
And the PHP (upload-image-ajax.php) ...
<?php
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory
if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = $_SESSION['poolid']. "." .$ext;
// check's valid format
if(in_array($ext, $valid_extensions)) {
$path = $path.strtolower($final_image);
//checking if file exsists, so we can overwrite it
if(file_exists("uploads/$final_image")) unlink("uploads/$final_image");
if(move_uploaded_file($tmp,$path)) {
echo "<img src='$path' />";
}
} else {
echo 'invalid file';
}
}
?>
The problem is that I'd like this image upload "form" to be included in a larger form. But when you click "upload" it tries to submit the larger, overall form. Is there a way to edit this to maybe just have a button HTML element (not a true submit button) and when that gets clicked, it performs the same AJAX call?
Or does AJAX need to occur as a result of a true form submission?
FYI, when you upload the image, it sends to server and shows a preview. So I'd like it to be part of a larger form with other questions. This is just one "question" where they can upload an image and see the preview BEFORE clicking to submit the overall, larger form.