alaboudi
alaboudi

Reputation: 3413

Laravel: Form with files sent via Ajax

Im trying to send a form to my php server but my Laravel validation says that my forms are empty. I am trying to upload photo albums. My form consists of a title(text), cover(image), and photos(image). I receive a 422 error (Unprocessable Entity). Below is the code

HTML

<form class="lajax" action="{{ action('AlbumController@store') }}" method="POST">
    <div class="form-group">
        <label>Album Name</label>
        <input type="text" name="name" class="form-control">                                                
    </div>

    <div class="form-group">
        <label for="coverFile">Album Cover Image</label>
        <input  name="cover" type="file" id="coverFile">
        <p class="help-block">Example block-level help text here.</p>
    </div>

    <div class="form-group">
        <label for="albumFiles">Album Images</label>
        <input type="file" name="photos[]" multiple>
    </div>

    <button type="submit" class="btn btn-primary">Create Album</button>
</form> 

The Jquery responsible for the ajax //object that will be fed into jquerys ajax method

            var ajax_options={
                    url: url,
                    method: method,
                    beforeSend: function(jqXHR,settings){
                        console.log(jqXHR);
                        console.log(settings);
                        if(optns.debug)
                            console.log('executing beforeSend function');
                        optns.lajaxBeforeSend($form,formData,jqXHR,settings);
                    },
                    success: function(data,textStatus,jqXHR){
                        if(optns.debug)
                            console.log('executing success function');
                        optns.lajaxSuccess($form,formData,data,textStatus,jqXHR)
                    },
                    error: function(jqXHR,textStatus,errorThrown){
                        if(optns.debug)
                            console.log('error encountered. ajax error function procked');
                        optns.lajaxError($form,formData,jqXHR,textStatus,errorThrown);

                        var errors = jqXHR.responseJSON;
                        console.log(errors);
                    },
                }

                //check if files are included in the submitted form if the method is not GET
                if($form.find('input:file').length && method!='GET'){
                    ajax_options.processData=false;
                    ajax_options.contentType=false;
                    ajax_options.cache=false;
                    ajax_options.data=formData;
                }


                if(optns.debug)
                    console.log('About to send ajax request');

                //sending request here
                $.ajax(ajax_options);

the laravel php file

    public function store(Request $request)
    {
      //request input verification rules
      $rules=[
        'name'=>'required',
        'cover'=>'required|image',
        'photos'=>'required|array',
        'photos.*'=>'image'
      ];

      //perform validation
      $this->validate($request,$rules);

      //rest of code
    }

Upvotes: 0

Views: 992

Answers (2)

Bandana Sahu
Bandana Sahu

Reputation: 284

Please change the button type as button because you want to send the data through ajax.

Also if you want to send data through ajax you can use formdata . In formdata , you can send all the image file and data to the server easily. Please refer this:

Here is the Jquery to send data to the server through ajax.

var issueTextFileData = new FormData();
let count = 0;

var imageName = 'issueTextFileData' + ++count;
issueTextFileData.append('singleImage', $('input[name=cover]')[0].files[0]);
issueTextFileData.append(imageName, $('input[name=photos[]]')[0].files[0]); 
issueTextFileData.append('albumName', $('input[name=name]')[0].files[0]);

// you can do validation for all files also.

             $.ajax({
                    url: "YOUR URL",
                    type: "post",
                    dataType: "json",
                    data: issueTextFileData,
                    contentType: false,
                    processData: false,
                    beforeSend: function () {

                    },
                    success: function (response) {
                        if (response.status === 200) {
                            toastr.success(response.message, {timeOut: 3000});
                        } else {
                            toastr.error(response.message, {timeOut: 3000});
                        }
                    }
                });

Upvotes: 1

Aizaz Shahid
Aizaz Shahid

Reputation: 23

Try adding enctype="multipart/form-data" files=true to your form tag

Upvotes: 0

Related Questions