midascodebreaker's avatar

Ajax Submit For Image Upload

I been doing all this all day , finding a way , searching thru google and laracast but it seems i cant find the correct guide or tutorial ,

at the moment here is my code this is my js script

function submitReceipt(id){
    var url = $('#postReceiptForm'+ id).attr('action');
    var formdata = $('#postReceiptForm' + id).serializeArray();

            $.ajax({
            url: url,
            dataType:'JSON',
            data: formdata,
            type:'post',
        }).done(function(data){
            
           Materialize.toast(data.message, 4000,'',function () {
            console.log(data);
           });

        }).fail(function () { // if Fail
            var errors = data.responseJSON;

            $.each(errors.message, function(index, error)
            {
             Materialize.toast(error, 4000,'',function(){
                //
            });
            });
            
          });

        
    }

here is my blade template

<form action="postReceipt" method="POST" id="postReceiptForm{{ $order->id }}" enctype="multipart/form-data" onsubmit="submitReceipt({{ $order->id }}); return false;">
    
               <input type="hidden" name="_token" value="{{ csrf_token() }}"/>
                  <input type="hidden" name="id" value="{{ $order->id }}"/>
                  <div class="file-field input-field small">
                      <div class="btn">
                        <span>Upload Your Receipt</span>
                        <input type="file" name="attachment">
                      </div>
                      <div class="file-path-wrapper">
                        <input class="file-path validate" type="text">
                      </div>
                  </div>
               <div class="modal-footer">
               <button class="col s6 pull-m1 m5 pull-l1 l5 teal lighten-3 btn-large modal-action modal-close waves-effect waves-light btn-flat" type="submit" name="action" >Upload Receipt</button>
      <a href="#!" class="col s6 push-m1 m5 push-l1 l5 left red lighten-2 btn-large modal-action modal-close waves-effect waves-light btn-flat">Close</a>
            </div>
            </form>

Normal issue im facing csrf token mismatch and File is NULL ...

Anyone can help me to get me thru with this would be Awesome thanks

0 likes
3 replies
Snapey's avatar

This is working for me and does not need any additional libraries.

    <script>
        var form = document.getElementById('import');
        var request = new XMLHttpRequest(),
              token = document.querySelector('meta[name="csrf-token"]').content;


        form.addEventListener('submit',function(e){
            e.preventDefault();
            var formdata = new FormData(form);

            request.open('post','/import');
            request.addEventListener("load",transferComplete);
            request.setRequestHeader('X-CSRF-TOKEN', token);
            request.send(formdata);

        });

        function transferComplete(data){
            response = JSON.parse(data.currentTarget.response);
            document.getElementById('feedback').innerHTML = response.message + ' ' + response.count + ' files uploaded';
            console.log(response.message);
        }
    </script>

I have a file import field;

        <form class="form-horizontal" action="import" id="import" method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="file" class="col-sm-2 control-label">Files:</label>
                            <div class="col-sm-10">
                                <input class="form-control" type="file" name="file[]" multiple />
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-primary">Submit Files</button>
                            </div>
                        </div>
                    </form>

The csrf token is passed to the page in a meta element in the head of the html

    <meta name="csrf-token" content="{{ csrf_token() }}" />

Controller gets files like;

        $files = $request->file('file');

        if(empty($files[0])){
            return \Response::json(array('message' => 'Error!', 'count' =>0));
        }

        foreach ($files as $file) {

            Storage::put($file->getClientOriginalName(),file_get_contents($file));

    // and then I go on and do other things with the files

I used this video for inspiration, but found a few issues such as csrf

https://youtu.be/--9I5wqXgUM

1 like

Please or to participate in this conversation.