Reputation: 153
I have written a jQuery script that checks for change event on a file input field, when a file is selected, the form submit function needs to be fired and post data via Ajax.
The Problem: Function on file change is being fired but the submit function is not being fired. The console has no errors to show.
Script that I have written:
$(document).ready(function() {
$("#upld").on('change', function() {
console.log('going to run submit function');
$('#fff').submit(function(e) {
console.log('submitting function executed')
var siteSettings = {"ajaxurl": '/filer/check/wp-admin/admin-ajax.php'};
var data = {
action: 'uploading-new-image',
files: $(this).serialize()
};
jQuery.post(
siteSettings.ajaxurl,
data,
function(response) {
$("#error").html(response);
});
e.preventDefault();
});
});
});
Here is the HTML:
<form id="fff" method="POST" action="process.php" enctype="multipart/form-data">
<input type="file" name="filetoupload" id="upld" />
</form>
Upvotes: 0
Views: 36
Reputation: 59292
You are not triggering it. You are just adding a handler for submit handler.
Add .submit()
or .trigger('submit')
to the code.
$(document).ready(function () {
$("#upld").on('change', function () {
console.log('going to run submit function');
$('#fff').submit(function (e) {
console.log('submitting function executed')
var siteSettings = {
"ajaxurl": '/filer/check/wp-admin/admin-ajax.php'
};
var data = {
action: 'uploading-new-image',
files: $(this).serialize()
};
jQuery.post(
siteSettings.ajaxurl,
data,
function (response) {
$("#error").html(response);
});
e.preventDefault();
}).submit(); // <-------- Added submit here.
});
});
Upvotes: 3