0

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

3
  • Can you show the javascript code you use to submit the form? Commented Mar 5, 2019 at 8:37
  • $('#addTask_form').on('submit', function(event){ event.preventDefault(); var form_data = $(this).serialize(); $.ajax({ url:"{{route('postdataroute')}}", method:"POST", data:form_data, dataType:"json", success:function(data) { if (data.error.length > 0) .................. Commented Mar 5, 2019 at 8:40
  • please add your javascript code in your question Commented Mar 5, 2019 at 9:27

2 Answers 2

1

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')
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.