JSFiddle - React, Tailwind, and code Playground

by manishie

HTML

<form name="product" method="post" action="#" class="smart-form" id="product-form" novalidate="novalidate" enctype="multipart/form-data">
    <label for="product_imageFile_file">File</label>
    <input class="valid" id="product_imageFile_file" name="product[imageFile][file]" type="file">
    </div>
    <button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> Guardar</button>
</form>

JavaScript

$(function () {
        $('.smart-form').on('submit', function (e) {
            var files;

            e.stopPropagation(); // Stop stuff happening
            e.preventDefault(); // Totally stop stuff happening

            if ($(".state-error").length < 1) {
                // Create a formdata object and add the files
                var data = new FormData();

                // Check for the various File API support.
                if (window.File && window.FileReader && window.FileList && window.Blob) {
                    // Grab the files and set them to our variable
                    //files = e.target.files;
                    files = $('form #product_imageFile_file')[0].files
                    
                    $.each(files, function (key, value) {
                        data.append(key, value);
                    });
                }

                // Create a jQuery object from the form
                $form = $(e.target);

                // Serialize the form data
                var formData = $form.serializeArray();

                $.ajax({
                    async: false,
                    url: 'some-url',
                    type: 'POST',
                    data: formData,
                    cache: false,
                    success: function (data, textStatus, jqXHR) {
                        if (typeof data.error === 'undefined') {
                            console.log('Success');
                        } else {
                            console.log('Errors');
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        // Handle errors here
                        console.log('Errors');
                    },
                    complete: function () {
                        // STOP LOADING SPINNER
                    }
                });
            }
        });
    });