1

I have a front end entry form which submits and saves fine when not using ajax. But when i do submit via ajax the text fields etc save fine but the file/assets field will not.

I have stripped it right back for testing but still not saving the file on ajax submit. I have even made the logged in user a full admin for testing purposes.

My Form:

<form method="post" id="applicationForm" class="sform2" accept-charset="UTF-8" enctype="multipart/form-data">
    {{ csrfInput() }}
    {{ actionInput('entries/save-entry') }}
    {{ hiddenInput('sectionId', '3') }}
    {{ hiddenInput('enabled', '1') }}
    {{ hiddenInput('entryId', '159') }}      

    <label for="nameAccountIsHeldIn" class="col-12 col-form-label">Name account is held in</label>

    <input type="text" name="fields[nameAccountIsHeldIn]" class="form-control" id="nameAccountIsHeldIn" value="">

    <input type="file" name="fields[accounts][]" class="form-control" id="accounts" multiple>
    <button type="submit" class="btn btn-primary">Submit</button>        

</form>  

js:

$('.sform2').submit(function(ev) {
    ev.preventDefault();

    startAlerts();
    var data = $(this).serialize();
    var url = $(this).attr("action");

    console.log($(this));
    console.log(data);


    $.ajax({
        type: 'POST',
        url: url,
        data: $(this).serialize() ,
        dataType : 'json', // changing data type to json
        success: function (response) { // here I'm adding data as a parameter which stores the response
            console.log(response); // instead of alert I'm changing this to console.log which logs all the response in console.
        }
    });

});
1

Finally found the answer after much time spent on it.

The $(this).serialize() loses the file input - and can't submit.

Updated ajax submit to

$.ajax({
    type: 'POST',
    url: url,
    data: new FormData(this) ,
    dataType : 'json', // changing data type to json
    processData: false,
    contentType: false,        
    success: function (response) { // here I'm adding data as a parameter which stores the response
        console.log(response); // instead of alert I'm changing this to console.log which logs all the response in console.
    }
});
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.