0

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>

View on JSFIDDLE

1 Answer 1

3

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.
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

thankyou, one more question please, how do I parse $_FILES data of the uploaded file via ajax so that I can deal with it on the Server side PHP script file?
@Jade, sorry! I don't know php :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.