im building an application with Laravel 4, in some point i want to add some model throught modal(Bootstrap) so i needed ajax to send my from, i have setup my route and action in controller, and then i have built the form markup with blade, i have wrote the ajax code, the request goes fine and i retrieve the inputs through Input facade, the problem here is that form has a file input, and when serialising form data with $('#formRub ').serialize(), it can't handle the file input, so i have to use FromData object and set the processData and contentType to false in the ajax request, the request sent, but i when u access to Input facade i got empty array !!
Route :
Route::post('/add', ['as' => 'rubrique.add.post', 'uses' => 'RubriquesController@ajaxaddpost']);
Controller :
class RubriquesController extends \BaseController {
public function ajaxaddpost(){
return dd(Input::all());
$v = Validator::make(Input::all(), Rubrique::$rules);
if($v->fails()){
return Response::json([
'fail' => true,
'errors' => $v->errors()->toArray()
]);
}
if(Input::hasFile('image'))
return Response::json(['success' => Input::file('image')]);
return Response::json(['fail' => 400]);
}
Markup :
{{ Form::open(['route' => 'rubrique.add.post', 'method' => 'post', 'files' => true, 'class' => 'form-horizontal', 'id' => 'rubForm']) }}
{{Form::label('name', 'Nom de la boutique :', ['class' => 'col-md-4 control-label'])}}
{{Form::text('name', null, ['class' => 'form-control', 'placeholder' => 'Entrer votre nom de boutique..'])}}
{{Form::label('desc', 'Description :', ['class' => 'col-md-4 control-label'])}}
{{Form::textarea('desc', null, ['class' => 'form-control', 'placeholder' => 'Enter votre e-mail..', 'rows' => '3'])}}
{{Form::label('image', 'Image :', ['class' => 'col-md-4 control-label'])}}
{{Form::file('image', ['class' => 'form-control', 'placeholder' => 'Enter votre e-mail..'])}}
{{Form::label('rubrique_id', 'Rubrique Parent :', ['class' => 'col-md-4 control-label'])}}
{{ Form::rubriques(0) }}
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
{{Form::submit('Ajouter', ['class' => 'btn btn-primary', 'id' => 'sendRubrique']) }}
</div>
</div>
{{Form::close()}}
JS:
$('#rubForm').submit(function(e){
e.preventDefault();
var $form = $( this ),
dataFrom = new FormData($form),
url = $form.attr( "action"),
method = $form.attr( "method" );
$.ajax({
url: url,
data: dataFrom,
type: method,
contentType: false,
processData: false
});
});