Laravel 4.2 and Ajax image upload

Asked

Viewed 157 times

1

I am trying to make an image upload, to save along with the rest of the fields, but when I press the save button, the picture field will empty..

This is the Form

<div class="panel">
  <div class="panel-heading">
     <h3><i class="fa fa-edit"></i>  <strong>{{ (isset($lisEventEdit)) ? Lang::get('admin/event.edit_event') : Lang::get('admin/event.new_event') }}</strong></h3>
  </div>
   <div id="new_edit_event">
     <div class="panel-body">
        @if(isset($lisEventEdit))
          {{ Form::model($lisEventEdit, array('url' => '/event/save', 'data-colllabel'=>'3','id'=>'formEvent', 'name'=>'formEvent','method'=>'post','onsubmit'=>'return false', 'files' => true )) }}         
        @else
          {{ Form::open(array('url' => '/event/save', 'data-colllabel'=>'3','id'=>'formEvent','name'=>'formEvent',  'method'=>'post','onsubmit'=>'return false', 'files' => true )) }}
        @endif
          {{ Form::hidden('id_event') }}

          <div class="col-lg-12">
            <div class="form-group row">
              <div class="col-md-6">
                 {{ Form::label ('id_status', Lang::get('admin/event.status')) }}
                 {{ Form::select('id_status', ["" => Lang::get('general.select')]+$status, null, ['class' => 'form-control', 'id'=>'status']) }}
              </div>
              <div class="col-md-6">
                 {{ Form::label ('entries', trans('admin/event.entries')) }}
                 {{ Form::text ('entrada', null, array('class' => 'form-control', 'placeholder' =>'')) }}   
              </div>
            </div>
          </div>

           <div class="col-lg-12">
             <div class="form-group row">
               <div class="col-md-6">
                  {{ Form::label ('data', Lang::get('admin/event.data')) }}
                  {{ Form::text('dt_event',"",array('class'=>'form-control date', 'placeholder' => '__/__/____')) }}
               </div>
             <div class="col-md-6">
                {{Form::label ('hour', Lang::get('admin/event.hour')) }}
                {{ Form::text('hr_event',"",array('class'=>'form-control time','placeholder'=>'HH:MM:SS')) }}
             </div>
           </div>

          <div class="col-lg-12">
            <div class="form-group row">
              <div class="select-contents" id="select-content-0">
                 {{Form::label ('image', Lang::get('admin/event.image')) }}
                 <div class="fileinput fileinput-new" data-provides="fileinput">
                   <div class="input-group">
                     <div class="form-control uneditable-input" data-trigger="fileinput">
                       <i class="glyphicon glyphicon-file fileinput-exists"></i>
                       <span class="fileinput-filename"> {{ $url or null }}</span>
                     </div>
                       <span class="input-group-addon btn btn-inverse btn-file">
                       <span class="fileinput-new">{{ Lang::get('admin/event.select_a_image')  }}</span>
                       <span class="fileinput-exists">{{ Lang::get('admin/event.change')  }}</span>
                       <input type="file" name="file"></span>
                       <a href="#" class="input-group-addon  btn btn-default fileinput-exists" data-dismiss="fileinput">{{ Lang::get('admin/event.remove')  }}</a>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          {{ Form::close() }} 
       </div>  

       <div class="panel-footer">
         <div class="form-group">
             {{ Form::submit(Lang::get('admin/event.save'), array('class' => 'btn btn-primary sendEvent','id'=>'sendEvent','name'=>'sendEvent')) }}
                <a href="/event" class="btn btn-primary">{{ Lang::get('admin/event.lists_all'); }}</a>
         </div>                    
       </div>

And this is Jquery

  $("#sendEvent").click(function () {

    $("#loadOverlaySaveNewEditRegister").fadeIn("fast");

    var form = $("#formEvent");

    $.ajax({
        type: "POST",
        url: "/event/save",
        dataType: "json",
        data: $("#formEvent").serialize()
    })

            .done(function (msg) {

                if (msg.status) {

                    $.notific8("{{Lang::get('admin/event.request_was_successfully')}}", {life: 1800, theme: "success", heading: ALERT_SUCCESS});

                    loadLists(1);

                    setTimeout(function () {
                        window.location.replace("/event/edit/" + msg.idEventEdit);
                    }, 2000);

                } else {

                    $.each(msg, function (key, val) {

                        $.notific8(val, {life: 5000, theme: "danger", heading: ALERT_ERROR});

                    });


                    $("#loadOverlaySaveNewEditRegister").delay(1000).fadeOut("slow");
                }

            });
});

Controller:

 public function eventSave(){

    $EventForm = new EventForm();

    if ($EventForm->validate()) {

        $post = $EventForm ->getNormalizedData(true);
        $post["dt_event"] = \Filter::dateToDateDb($post["dt_event"]);

        $nameFileOriginal = $post['file']->getClientOriginalName();
        $nameFile = md5(strtolower(preg_replace('/[^A-Za-z0-9\-]/', '', $nameFileOriginal) . rand(9, 99999)));
        $extensionFile = "." . $post['file']->getClientOriginalExtension();
        $pathFile = "/storage/event/";

        //NOME DO ARQUIVO
        $fileName = $nameFile . $extensionFile;

        $idEventEdit = $post['id_event'];
        $existsEvent = Event::where('id_event', '=', $idEventEdit )->first();

        if ($existsEvent ) {

            //update Event
            if ($existsEvent->update($post)) {

                $return = array("status" => true, "idEventEdit" => $existsEvent ->id_event);

                $idEventSaved = $existsEvent->id_event;
            } else {

                $return = array("status" => false, "type" => "update");
            }
        } else {

            //insert new Event
            if ($newEvent = Event::create($post)) {

                $return = array("status" => true, "idEventEdit" => $newEvent->id_event);

                $idEventSaved = $newEvent->id_event;
            } else {

                $return = array("status" => false, "type" => "insert");
            }
        }
        //End Event


        return \Response::json($return);
    } else {
        return \Response::json($EventForm->getMessages()->all());
    }
}

I’m pretty sure there’s something missing from Jquery and/or contoller, but I can’t figure out what, if anyone can help there, please. I really appreciate!

1 answer

2

The serialize of jQuery ($("#formEvent").serialize()) can’t stand it <input type=file>, have to adjust this using FormData, as I explained in: /a/77280/3635

The code could go something like:

//Pega todos elementos do form
var inputs = $('#formEvent input[name], #formEvent select[name], #formEvent textarea[name]');

//Inicia o FormData
var dados = new FormData;

//Itera todos elementos
inputs.each(function () {

    //Se for um input file adiciona files[0]
    if (this.getAttribute("type") === "file") {
        dados.append(this.getAttribute("name"), this.files[0]);
    } else {

        //Se for outros tipos de input, select ou textarea
        dados.append(this.getAttribute("name"), this.value);
    }
});

And in Ajax add processData: false and in data: pass the variable dados, thus:

$.ajax({
    type: "POST",
    url: "/event/save",
    dataType: "json",
    processData: false,
    data: dados
})
  • Thank you William! It worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.