Jetmir Sylejmani
Jetmir Sylejmani

Reputation: 3

Laravel upload file using Ajax

I'm trying to create upload function in Laravel 5.7 using Ajax request. I'm getting null value in the database after writing this code. So, all other data are being inserted except the file that is returning empty value.

tasks.blade.php

<form method="post" id="addTask_form" name="addtask" enctype="multipart/form-data">
      .......................
            <div class="form-group">
                <label>File</label>
                 <input type="file" name="file" id="file">
            </div>
            .............


        </div>                 

      <div class="modal-footer">
       ................
      </div>
      </form>

TasksController.php

 function postdata(Request $request)
{
    $validation = Validator::make($request->all(), [
        .......
        'file' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',    
        'status' => 'required',

        ]);

   .............
    if ($validation->fails())
    {
        foreach ($validation->messages()->getMessages() as $field_name => $messages)
        {
            ...........
        }
    }
    else
    {
        if($request->get('button_action') == 'insert')
        {


            if($request->hasFile('file') && $request->file('file')->isValid()){
                $file = $request->file('file');
                $file_name = str_random(30) . '.' . $file->getClientOriginalExtension();
                $file->move(base_path() . '/assets/img', $file_name);
            }
            $task = new Task($request->input());

            $task->save();


    }


    $output = array(
        'error'     =>  $error_array,
        'success'   =>  $success_output
    );
    echo json_encode($output);
}

Thank you

Upvotes: 0

Views: 1963

Answers (2)

Akash Kumar Verma
Akash Kumar Verma

Reputation: 3318

You can not upload image using serialize(). you need to use FormData() with these properties;

 contentType: false,
 processData: false,
    var data = new FormData($('#addTask_form')[0]);
    $.ajax({
        url: "{{route('postdataroute')}}",
        data: data,
        type: 'POST',
        contentType: false,
        processData: false,
        success: function (data) {

        }      
    }); 
  1. if you don't want to send csrf token

then

    app/Http/Middleware/VerifyCsrfToken.php

and add this route's url to the except array

    protected $except = [
    'your route url'
    ];
  1. if want

then add in head

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

and in script

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

Upvotes: 1

Kelvin
Kelvin

Reputation: 1114

You can use FormData method to upload a file using Ajax Request on POST

$(document).on('submit', '#yourFormId', function(e){
  e.preventDefault();

  var form_data = new FormData($('#yourFormId')[0]); // this method will send the file request and the post data 
  form_data.append("_token","{{csrf_token()}}") //for csrf token
  $.ajax({
      type:'POST',
      url:'{{route('yourRoute')}}',
      async: false,
      cache: false,
      data : form_data,
      success: function(response){

      }
  });
});

basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.

While cache will force browser to not cache uploaded data to get updated data in ajax request

Referrer on How to upload file using Ajax On Post

Upvotes: 0

Related Questions