0

Currently I have working save data using ajax and laravel. But when I tried to add image field on saving it doesn't work properly now.

First I can pass variables with values using ajax to my controller.

these are my variables name, type, select_file, steps, step_no

If I didn't fill up one of those fields it will prompt an error message.

I can get the file name of the select_file field and validate it on my controller.

How ever when I'm trying save and all fields are filled up this gives me an error like this

The select_file must be an image

enter image description here

Error prompts even though it has an image png file.

Here's my HTML

    <div class="modal fade" id="modalRecipes" tabindex="-1" role="dialog">

 <div class="modal-dialog" role="document">
    <div class="modal-content">
  <!--Header-->
  <div class="modal-header">
    <h4 class="modal-title" id="myModalLabel">Recipes</h4>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
       <span aria-hidden="true">×</span>
       </button>
      </div>
     <!--Body-->
       <div class="modal-body">
    <div class="container">
        <form>
        {{ csrf_field() }}

            <div class="form-group row">
                <label for="name" class="col-md-4 col-form-label text-md-right">Name</label>

                <div class="col-md-6">
                    <input type="text" class="form-control name" name="name" id="name">
                </div>
            </div>

            <div class="form-group row">
                <label for="type" class="col-md-4 col-form-label text-md-right">Type</label>

                <div class="col-md-6">
                     <select class="form-control type" name="type" id="type">

                     </select>
                </div>
            </div>

            <div class="form-group row">
                <label for="select_file" class="col-md-4 col-form-label text-md-right">Select Image</label>

                <div class="col-md-6">
                     <input type="file" name="select_file" id="select_file" />
                </div>
            </div>



            <div class="optionBox">
              <div class="block step">
                <div class="form-group">
                  <label for="step1">Step 1</label>
                  <textarea name="steps" data-steps="1" class="form-control rounded-0 steps" id="step1" rows="10"></textarea>
                </div>
              </div>

            </div>
            <div class="">
                <span class="add">Add Option</span>
              </div>

        </form>
    </div>


  </div>
  <!--Footer-->
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-success" data-dismiss="modal">Close</button>
    <button type="button" name="submit" class="btn btn-success waves-effect" id="btnSubmit">Submit</button>
        </form>
  </div>
</div>

and here's my AJAX

 $(document).ready(function () {
    $("#btnSubmit").click(function () {
        var name = $("#name").val();
        var type = $("#type").val();
        var select_file = $("#select_file").val();

        var steps = [],
            step_no = [];
        $('textarea[name="steps"]').each(function() {
            steps.push($(this).val());
            step_no.push($(this).attr('data-steps'));
        });


        var x = document.getElementById("btnSubmit");
        x.innerHTML = "Loading...";
         document.getElementById("btnSubmit").disabled = true;

         $.ajax({
            headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            url: "{{ route('insert') }}",
            method: "POST",
            data:{
                name:name,
                type:type,
                steps:steps,
                step_no:step_no,
                select_file:select_file
            },
            dataType: "json",
            success:function(data)
            {
                if (data.success.length > 0) {
                    location.reload();
                } else {
                    toastr.error(data.error[0]);
                    var x = document.getElementById("btnSubmit");
                    x.innerHTML = "Submit";
                     document.getElementById("btnSubmit").disabled = false;
                }
            },
            error: function(xhr, ajaxOptions, thrownError){
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });

    });
});

And here's my Controller

public function insert(Request $request)
{
    $message = "";
    $output = array();
    $error = array();
    $success = array();

    $validator = Validator::make($request->all(), [
      'select_file'=>'image',
      'name' => 'required',
      'type' => 'required',
      'steps' => 'required',
      'step_no' => 'required'
    ]);

    if ($validator->fails()) {
        $messages = $validator->errors()->all();
        $error[] = $messages; 
    } else {
        $dateTime = date('Ymd_His');
        $image = $request->select_file;
        $new_name = $dateTime . '.' . $image->getClientOriginalExtension();
        $image->move(public_path('img'), $new_name);


       // Code for saving data.....

        $messages = "Successfully Saved!";
        $success[] = $messages; 

    }

    $output = array(
        'error'=>$error,
        'success'=>$success
    );

    echo json_encode($output);
}
Pablo
  • 1,357
  • 1
  • 11
  • 40
  • You need to upload binary data using a `FormData` object, not a form-urlencoded string: https://stackoverflow.com/a/10899796/519413. I can't help with the Laravel side of things, though. – Rory McCrossan Apr 02 '20 at 14:06
  • Uploading image via js/jquery is tricky take a look at https://makitweb.com/how-to-upload-image-file-using-ajax-and-jquery/ and https://stackoverflow.com/questions/19447435/ajax-upload-image – AH.Pooladvand Apr 02 '20 at 14:08

0 Answers0