jeudi 26 novembre 2020

How to send some data and image from AJAX to Controller in Laravel?

I'm a freshmen in the office and I was assigned by my boss to fix the code of the website that the developer is not in the company anymore. He used mostly AJAX to do things which I'm not used to it. I rarely use AJAX in my project, so I'm very very new about this.

From the old code, I'm trying to send an image with some data from an input form. I can console.log(form_data) to see its values, but I don't know why the content of image cannot be sent to Controller. It's getting 'null' and I can't store it.

Here is the code in input form

<div class="modal-dialog">
<div class="modal-content">
    <div class="modal-header">
      <h4 class="modal-title"></h4>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <form id="input-form" class="needs-validation" novalidate method="POST" enctype="multipart/form-data" name="input-form">
        
        <div class="form-horizontal">
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="thai_name"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="thai_name" name="thai_name" value="" required/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="eng_name"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="eng_name" name="eng_name" value="" required/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="email"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="email" name="email" value="" required/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="password"></label>
            <div class="col-sm-12">
              <input type="password" id="password" class="form-control" required/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="password_confirmation"></label>
            <div class="col-sm-12">
              <input type="password" id="password_confirmation" class="form-control" required/>
            </div>
          </div>
          <div class="form-group col-sm-12">
            <a class="btn-link" id="message" style="text-align: center;"></a>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label" for="phone"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="phone" name="phone" value="" required/>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-12 control-label" for="fax"></label>
            <div class="col-sm-12">
              <input type="text" class="form-control" id="fax" name="fax" value=""/>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label"></label>
            <div class="col-sm-12">
              <div class="form-check form-check-inline">
                <input class="form-check-input role" type="radio" id="admin" name="role" value="1"
                 required>
                <label class="form-check-label" for="admin">ผู้ดูแลระบบ</label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input role" type="radio" id="content_admin" name="role" value="2"
                 required>
                <label class="form-check-label" for="content_admin">ผู้ดูแลข้อมูล</label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input role" type="radio" id="user" name="role" value="3"
                 required>
                <label class="form-check-label" for="user">ผู้ใช้งาน</label>
              </div>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label"></label>
            <div class="col-sm-12">
              <select id="faction" class="form-control">
                @foreach($factions as $faction)
                  <option value="" >
                    
                  </option>>
                @endforeach
              </select>
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-12 control-label"></label>
            <div class="col-sm-12">
              <select id="position" class="form-control">
                @foreach($positions as $position)
                  <option value="" >
                    
                  </option>>
                @endforeach
              </select>
            </div>
          </div>
          <div class="form-group required">
            <div class="col-sm-12">
              <label class="control-label" for="photo">รูปถ่าย</label>
              <input type="file" class="form-control-file" id="photo" name="photo" accept="image/*" required/>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-12 control-label"> / </label>
            <div class="col-sm-12">
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="checkbox" id="acting" name="acting" >
                <label class="form-check-label" for="acting"></label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="checkbox" id="past" name="past" >
                <label class="form-check-label" for="past"></label>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-12" for="start"></label>
            <div class="col-sm-12">
              <div class="input-group" id="start" name="start">
                <input type="text" class="form-control" readonly="readonly"/>
                <div class="input-group-append">
                  <span class="input-group-text input-group-addon">
                    <span class="fa fa-calendar"></span>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-12" for="end"></label>
            <div class="col-sm-12">
              <div class="input-group" id="end" name="end">
                <input type="text" class="form-control" readonly="readonly"/>
                <div class="input-group-append">
                  <span class="input-group-text input-group-addon">
                    <span class="fa fa-calendar"></span>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row col-sm-12 text-center">
              <input type="button" class="btn btn-default" value=""
                     onclick=""
                     />
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>
<script type="text/javascript">
$(function () {
  $('#start').datetimepicker({
    sideBySide: true,
    locale: 'th',
    format: 'YYYY-MM-DD',
    ignoreReadonly: true,
    defaultDate: ""
  });
  $('#end').datetimepicker({
    sideBySide: true,
    locale: 'th',
    format: 'YYYY-MM-DD',
    ignoreReadonly: true,
    defaultDate: ""
  });
  $('#password, #password_confirmation').on('keyup', function () {
      if ( $('#password').val() == $('#password_confirmation').val() ) {
        if ( $('#password').val() != '') {
          $('#message').html('').css('color', 'green');
        } else {
          $('#message').html('').css('color', 'red');
          $('#password').removeClass('valid').addClass('invalid');
          $('#password_confirmation').removeClass('valid').addClass('invalid');
        }
      } else {
        $('#message').html('').css('color', 'red');
        $('#password').removeClass('valid').addClass('invalid');
        $('#password_confirmation').removeClass('valid').addClass('invalid');
      }
    });
});
</script>

Here is the code in user.js where I'm using AJAX to send form_data contains image and some data

function addUser() {
 var validate = validateUser("add");
  if (validate.error == '') {
    $('#modal1').modal({backdrop: "static"});
    var form_data = {
      thai_name: validate.thai_name,
        eng_name: validate.eng_name,
      email: validate.email,
      password: validate.password,
      password_confirmation: validate.password_confirmation,
      telephone: $('#phone').val(),
      fax: $('#fax').val(),
      system_role_id: $('input[name=role]:checked').val(),
      faction_id: $('#faction').val(),
      position_id: $('#position').val(),
      photo: $('#photo').val(),
      photo_file: $('#photo').prop("files")[0],
      is_acting: 0,
      is_past: 0,
      start: $('#start').data('date'),
      end: $('#end').data('date'),
    };

    if ($('#acting').is(':checked')) {
      form_data.is_acting = 1;
    }
    if ($('#past').is(':checked')) {
      form_data.is_past = 1;
    }

    console.log(form_data);

    $.ajax({
        type: "post",
      enctype: "multipart/form-data",
      url: baseurl + "/admin/user/add",
      data: form_data,
      processData: false,
      contentType: false,
      headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function () {
            $('#input-area').modal('hide');
            listUser();
        }
    });
  }
}

Here is some code in my controller

public function addUser(Request $request) {
  $user = new User();
  $user->thai_name = request()->thai_name;
  $user->eng_name = request()->eng_name;
  $user->email = request()->email;
  $user->password = Hash::make(request()->password);
  $user->telephone = request()->telephone;
  $user->fax = request()->fax;
  $user->system_role_id = request()->system_role_id;
  $user->faction_id = request()->faction_id;
  $user->position_id = request()->position_id;

  // Store Profile Photo
  $filename = "profile-photo-" . time() . "-name-" . basename(request()->photo);
  request()->file('photo_file')->storeAs('', $filename, 'images');
  $user->photo = $filename;

  $user->is_acting = request()->is_acting;
  $user->is_past = request()->is_past;
  $user->start = request()->start;
  $user->end = request()->end;
  $user->save();
}

Which part I did wrong? Any ideas? Please help me figure this out. Thank you in advanced.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire