Reputation: 85
I have a form and a input type file inside.
<form id='imageform' method='post' enctype='multipart/form-data' action='php/exec/add-message-image-exec.php' style='clear:both'>
<div id='imageloadstatus' style='display:none'><img src='assets/loader.gif' alt='Uploading....'/></div>
<div id='imageloadbutton'>
<div class='file-field input-field'>
<div class='btn'>
<span>Upload</span>
<input type='file' name='file' id='photoimg'/>
</div>
<div class='file-path-wrapper'>
<input class='file-path validate' type='text'>
</div>
</div>
</div>
</form>
It performs whenever i attach an image in the input file, and an ajax will handle it to submit it automatically and save it to the database.
$(document).ready(function () {
$('#photoimg').on('change', function () {
var A = $('#imageloadstatus');
var B = $('#imageloadbutton');
$('#imageform').ajaxSubmit({target: '#preview',
beforeSubmit: function () {
A.show();
B.hide();
},
success: function () {
A.hide();
B.show();
},
error: function () {
A.hide();
B.show();
}}).submit();
});
});
My problem is that it submits the image twice and save it to my database/table twice. But when i remove the .submit();
inside my script, it only perform once but there's a small modal-like window and another screen appeared whenever i attach an image/submit.
Upvotes: 2
Views: 105
Reputation: 178
Remove 'action' and put it in an ajax POST request instead.
$(document).ready(function () {
$('#photoimg').on('change', function () {
var A = $('#imageloadstatus');
var B = $('#imageloadbutton');
$.ajax({
url: 'php/exec/add-message-image-exec.php',
type: 'POST',
data: $('#imageform').serialize(),
beforeSubmit: function () {
A.show();
B.hide();
},
success: function (data) {
//do something with data
//ex: console.log()
console.log(data);
A.hide();
B.show();
},
error: function () {
A.hide();
B.show();
}
});
});
});
Upvotes: 2