Christian Gimenez
Christian Gimenez

Reputation: 81

php - jquery ajax Laravel 5.2 $request->file is null

Jquery Ajax

the ajax request

$.ajax({
                    type: 'POST',
                    url: 'Enviar_Solicitud',
                    data: {
                        'nombres': $('input[name=ModTextNombres]').val(),
                        'email': $('input[name=ModTextEmail]').val(),
                        'categoria': $('select[name=ModSelctCategoria]').val(),
                        'descripcion': $('textarea[name=ModTextAreaDescripcion]').val(),
                        'referencia': $('input[name=ModFilArchReferencia]').val()
                    },
                    cache: false,
                    success: function (data) {
                        if (data.Success == true) {
                            toastr.success(data.Message);
                        }
                    },
                    error: function (jqXhr) {
                        if (jqXhr.status === 422) {
                            var errors = jqXhr.responseJSON;
                            errorsHtml = '<ul>';
                            $.each(errors , function(key, value) {
                                errorsHtml += '<li>' + value[0] + '</li>';
                            });
                            errorsHtml += '</ul>';
                            toastr.error(errorsHtml);
                        }
                    }
                });

Form Blade

the form blade whith the correct files => true

<div class="modal-body">
              {!! Form::open(array("class" => "form-horizontal", "name" => "FormEnviarPresupuesto", "role" => "form", "files" => true, "data-toggle" => "validator")) !!}
              <div class="form-group">
                {!! Form::label("LablNombres", "Nombres", array("class" => "col-md-2 control-label")) !!}
                <div class="col-lg-8">
                  {!! Form::text("ModTextNombres", null, array("class" => "form-control input-md", "placeholder" => "Nombres", "pattern" => "[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+", "required" => "")) !!}
                  <div class="help-block with-errors"></div>
                </div>
              </div>
              <div class="form-group">
                {!! Form::label("LablEmail", "Email", array("class" => "col-md-2 control-label")) !!}
                <div class="col-md-8">
                  {!! Form::email("ModTextEmail", null, array("class" => "form-control input-md", "placeholder" => "[email protected]", "required" => "")) !!}
                  <div class="help-block with-errors"></div>
                </div>
              </div>
              <div class="form-group">
                {!! Form::label("LablCategoria", "Categoría", array("class" => "col-md-2 control-label")) !!}
                <div class="col-lg-8">
                  {!! Form::select("ModSelctCategoria", array("1" => "Nuestro Software", "2" => "Sistema Personalizado", "3" => "Web Auto-Administrable", "4" => "CMS", "5" => "Mantenimiento"), null, array("class" => "form-control", "placeholder" => "Seleccione...")) !!}
                </div>
              </div>
              <div class="form-group">
                {!! Form::label("LablDescripcion", "Descripción", array("class" => "col-md-2 control-label")) !!}
                <div class="col-md-8">
                  {!! Form::textarea("ModTextAreaDescripcion", null, array("class" => "form-control", "rows" => "6", "required" => "")) !!}
                  <div class="help-block with-errors"></div>
                </div>
              </div>
              <div class="form-group">
                {!! Form::label("LablArchReferencia", "Referencia", array("class" => "col-md-2 control-label")) !!}
                <div>
                  {!! Form::file("ModFilArchReferencia", null, array("class" => "input-file")) !!}
                </div>
              </div>
              <div class="form-group text-center">
                {!! Form::button("<i class='fa fa-check fa-lg'></i> Enviar Solicitud", array("class" => "btn btn-lg btn-success", "name" => "BtnEnviarSolicitud", "type" => "submit")) !!}
              </div>
              {!! Form::close() !!}
            </div>

Controller

the controller. in laravel 5.0 this work but in this version 5.2 not working because $request->file("referencia") return null

namespace App\Http\Controllers;

use Request;
use App\SolicitudModel;
use App\Http\Requests\SolicitudFormRequest;


class SolicitudController extends Controller
{

    public function GuardarSolicitud (SolicitudFormRequest $request)
    {
        if (Request::ajax())
        {
            $_solicitud = new SolicitudModel;
            $_solicitud->nombres = $request->get("nombres");
            $_solicitud->email = $request->get("email");
            $_solicitud->categoria = $request->get("categoria");
            $_solicitud->descripcion = $request->get('descripcion');

            $_solicitud->referencia = $request->file("referencia")->getClientOriginalName();
            $name = $request->file("referencia")->getClientOriginalName();
            $request->file("referencia")->getClientOriginalExtension();
            $request->file("referencia")->move(base_path() . '/public', $name);
            $_solicitud->save();
            return response()->json(["Success" => true]);
        }
    }

}

Upvotes: 1

Views: 2652

Answers (2)

Rafiq
Rafiq

Reputation: 11445

I wrote this code for Laravel 6, anyway you can use html and js codes for any platform, if you are using laravel framework first you have to run a command by using terminal/command line to create a folder in your project public directory named 'storage' php artisan storage:link

html:

<form id="form_id" enctype="multipart/form-data">
        <div class="from-group">
            <label for="title">App name:</label>
            <input type="text" name="title" id ="title_id" class="form-control" placeholder="App name"><br>
        </div>
        <br>
        <div class="form-group">
            <input type="file" id="image" name="cover_image" autocomplete="off" class="form-control" />
           </div>
        <button type="button" onclick="WebApp.CategoryController.onClickAppSubmitButton()" class="btn btn-primary">Submit </button>
    </form>

js:

WebApp.CategoryController.onClickAppSubmitButton = function (){   
    var title = document.getElementById("title").value;
    var messageView = $('.messages');
    var messageHtml = "";
    if (title == null || title == "") {
        messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger", "Title should not empty");
        $(messageView).html(messageHtml);
        return;
    }

    var form = $("#form_id")[0];
    var formData = new FormData(form);
    formData.append('parent_id','0');
    $.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: url_app_post,
        method: "POST",
        contentType: false,
        processData: false,
        data: formData,
        success: function (result) {
            var data_array = $.parseJSON(result);
            if (data_array.status == "200") {
                messageHtml += WebApp.CategoryController.getAlertMessage("alert-success", data_array.message);
            } else {
                messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger", data_array.message);
            }

            $(messageView).html(messageHtml);
        },
        error: function (jqXHR, exception) {
            messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger",
                WebApp.CategoryController.getjqXHRmessage(jqXHR, exception));

            $(messageView).html(messageHtml);
        }

    })
}

Controller:

public function storecat(Request $request){
        if($this->checkforExist($request)  !== null){
            $output = array("message"=>"This category name already exist", "status" => "403");
            return json_encode($output);
        }
        echo $this->storeCategory($request, "Category");

    }

    function checkforExist(Request $request){
            return DB:: table('categories')
            ->where('title',$request->title)
            ->get()->first();
    }
    function storeCategory(Request $request, $type){
        try{
            $fileNameToStore='no_image.jpg';
            if($request->hasFile('cover_image')){
                $fileNameWithExt = $request->file('cover_image')->getClientOriginalName();
                $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
                $extension = $request->file('cover_image')->getClientOriginalExtension();
                $fileNameToStore=$fileName.'_'.time().'.'.$extension;
                $path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);

            }
            $cat = new Category();
            $cat->title = $request->title;
            $cat->parent_id = $request->parent_id;
            $cat->cover_image=$fileNameToStore;
            $cat->user_id=auth()->user()->id;
            $cat->save();
            return json_encode(array("message"=>"The ".$type." successfully added", "status" => "200"));

        }catch(Exception $e){
            return  json_encode(array("message"=>$type." failed to insert: ".$e->getMessage(), "status" => "403"));
        }

    }

Finally pulling image from storage:

 <td><img width="50" height="50" src="/storage/cover_images/{{$cat->cover_image}}"></td>

Upvotes: 0

Claudio King
Claudio King

Reputation: 1616

Files cannot be serialized as a normal post request, they must be sent using multipart/form-data enctype, so in the form tag you have to place:

{!! Form::open(array("class" => "form-horizontal", "name" => "FormEnviarPresupuesto", "role" => "form", "files" => true, "data-toggle" => "validator", "enctype" => "multipart/form-data")) !!}

And pass FormData Object to Jquery Ajax function:

var formData = new FormData($('form')[0]); //select your form
$.ajax({
    type: 'POST',
    url: 'Enviar_Solicitud',
    data: formData, //pass the formdata object
    cache: false,
    contentType: false, //tell jquery to avoid some checks
    processData: false,
    success: function (data) {
        if (data.Success == true) {
            toastr.success(data.Message);
        }
    },
    error: function (jqXhr) {
        if (jqXhr.status === 422) {
            var errors = jqXhr.responseJSON;
            errorsHtml = '<ul>';
            $.each(errors , function(key, value) {
                errorsHtml += '<li>' + value[0] + '</li>';
            });
            errorsHtml += '</ul>';
            toastr.error(errorsHtml);
        }
    }
});

Upvotes: 4

Related Questions