1

I have a Laravel application and it has a form which submits its data using an Ajax call, submitted data is handled by a Laravel backend. All works fine for text data but I need to add a file upload to it, but when I'm trying to submit the data using the same code, it doesn't work.

This form is a Laravel component,

<form class="form-horizontal" action="@yield('content-form-action')" name="mfrm" id="mfrm" method="post" autocomplete="off" enctype="multipart/form-data">

Ajax call,

function saveData() {
    var applicationId = $('#applicationId').val();
    var jobReqId = $('#jobReqId').val();
    var attachment = $('#atcb').val();
    var prefix = $('#prefix').val();
    var famName = $('#famname').val();
    var nic = $('#nic').val();

    var dataObject = {
        applicationId: applicationId,
        attachment: attachment,
        jobReqId: jobReqId,
        prefix: prefix,
        famName: famName,
        nic: nic,
    }

    $.ajax({
        type: "POST",
        url: applicationAttachingFormSubmitUrl,
        async: false,
        data: dataObject,
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        beforeSend: function () {
            cursorWait();
            add_panelLoader($('#application-insert-form'));
        },
        success: function (status) {
            if (status.alert['type'] == "success") {
                getApplicationData();
                successAlert(status.alert['mssg'], status.alert['burl'], status.alert['rfms']);
            } else if (status.alert['type'] == "danger") {
                dangerAlert(status.alert['mssg'], status.alert['burl'], status.alert['rfms']);
            } else if (status.alert['type'] == "info") {
                infoAlert(status.alert['mssg'], status.alert['burl'], '');
            } else if (status.alert['type'] == "warning") {
                warningAlert(status.alert['mssg'], status.alert['burl'], '');
            }

            remove_panelLoader($('#application-insert-form'));
            cursorDefault();
            formclear();
        },
        error: function () {
            remove_panelLoader($('#application-insert-form'));
            cursorDefault();
        },
    }).fail(function (xhr, status, textStatus, error) {
        located(xhr);
    });
}

I have tried below way but not working. This is the way mentioned in other solutions and tutorials. If you need more details to get something clarified, I can update the code. TIA!

function saveData() {
    $('mfrm').submit(function(event){

        event.preventDefault();
        var formData = new FormData($(this)[0]);
        $.ajax({
            headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') },
            url: applicationAttachingFormSubmitUrl,
            data: formData,
            type: 'post',
            async: false,
            processData: false,
            contentType: false,
            success:function(response){
                console.log(response);
                alert('uploaded');
            },
            error: function () {
                console.log('error');
            },
        });

    });
}
pasindu
  • 529
  • 1
  • 4
  • 16
  • The php code handles the file so please share that. It should look for 'attachment' in the request. But this line is wrong: attachment = $('#atcb').val(); https://makitweb.com/a-step-by-step-guide-to-file-upload-with-php-ajax-and-jquery/ – marius-ciclistu Apr 23 '23 at 20:18
  • Hi @marius-ciclistu, May I know why is `attachment = $('#atcb').val();` wrong? and do you need the code in the controller? – pasindu Apr 24 '23 at 03:08
  • Yes the code from php that fetches the file from response. $file = $request->file('file'); if (!$file instanceof UploadedFile) { throw new \Exception('Missing file.'); } Also have a look here https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/Ajax-JavaScript-file-upload-example – marius-ciclistu Apr 24 '23 at 05:27
  • `$('mfrm').submit(`- `$('mfrm')` would select an element with the _tag name_ `mfrm`. There is no such HTML element. – CBroe Apr 24 '23 at 08:43

1 Answers1

1

Try removing $('mfrm').submit(function(event){ part from the JS.

jayanada
  • 66
  • 6