Send files and inputs with the same Ajax request

5

I have a code that works perfectly for sending files without refresh using PHP and jQuery and I have another code that works without refresh too but for insertion of data in the DB. I can not put the two codes together.

What I want is basically to send the data and upload a file using the same form and a single request. I believe the problem is in the "data:" attribute

jQuery Code - Sends Inputs:

    $( "#create" ).on( "click", function() {
        formId   = $(this).closest( ".form" ).attr("id");
        formArray = $("#" + formId).serializeArray();
        $.ajax({
            type: 'POST', url: 'ajax.php',
            data: { type: 'create', formArray: formArray },
            success: function( msg ) {
                alert( msg );
                window.location.reload();
            },
            error: function() {
                alert('AJAX Error');
            }
        });
        event.preventDefault();
    });

jQuery Code - Uploading Files:

    var form;
    $('#fileUpload').change(function (event) {
        form = new FormData();
        form.append('fileUpload', event.target.files[0]);
    });

    $( "#teste" ).on( "click", function() {
        $.ajax({
            type: 'POST', url: 'ajax.php',
            processData: false,
            contentType: false,
            data: form,
            success: function( msg ) {
                alert( msg );
            },
            error: function() {
                alert('AJAX Error');
            }
        });
        event.preventDefault();
    });
    
asked by anonymous 05.06.2014 / 19:10

1 answer

2

Think of your application as a template and see what makes the most sense: A registered user with no uploaded file or uploaded file not associated with any registered user?

If you were able to see a relationship, you can understand that it makes sense that the upload routine occurs in the successful callback of the user's registry. ;)

If the user's registration fails, it is a general failure, and therefore you will not have orphaned files. if the upload fails, at least the user already exists, with primary ID inclusive, which may allow future submission (s).

    
05.06.2014 / 19:33