2

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
            });
        });
2
  • Try this plugin blueimp.github.io/jQuery-File-Upload Commented Oct 2, 2014 at 10:06
  • i dont want a plugin for uploading, i just need an upload in this form only, so can you help me why this won't work ? Commented Oct 2, 2014 at 10:20

3 Answers 3

3

The key are in your ajax request. In the controller you can do whatever you want.

var form = document.forms.namedItem("yourformname"); // high importance!, here you need change "yourformname" with the name of your form
var formdata = new FormData(form); // high importance!

$.ajax({
    async: true,
    type: "POST",
    dataType: "json", // or html if you want...
    contentType: false, // high importance!
    url: '{{ action('yourController@postMethod') }}', // you need change it.
    data: formdata, // high importance!
    processData: false, // high importance!
    success: function (data) {

        //do thing with data....

    },
    timeout: 10000
});
Sign up to request clarification or add additional context in comments.

Comments

2

Your JavaScript should look like this:

$('#rubForm').submit(function(e){
    e.preventDefault();
    var $form = $( this ),
        dataFrom = $form.serialize(),
        url = $form.attr( "action"),
        method = $form.attr( "method" );

    $.ajax({
        url: url,
        data: dataFrom,
        type: method,
        processData: false
    });
});

You should use $form.serialize() and you have to remove contentType: false,

Now if you put into your controller for example something like this:

file_put_contents("test.txt", var_export(Input::all(), true));

it will create file with data in it however I don't know if it will work for file input

EDIT

I didn't notice seralize() and file input in the question, so now, you should add name attribute to your form:

 {{ Form::open(['route' => 'rubrique.add.post', 'method' => 'post', 'files' => true, 'class' => 'form-horizontal', 'id' => 'rubForm', 'name' =>'myform']) }}

and use the following code:

$('#rubForm').submit(function(e){
    e.preventDefault();
    var $form = $( this ),

        dataFrom = new FormData(document.forms.namedItem("myform"));
        url = $form.attr( "action"),
        method = $form.attr( "method" );

    $.ajax({
        url: url,
        data: dataFrom,
        type: method,
        processData: false
    });
});

3 Comments

i dont think you have read my question description, i have already did that but $form.serialize doesn't work with files !!
thank you sooooo much !! you saved my life !!, but if you know why the normal selector didn't work ? what with document.forms ??
@Ilyass I don't know why you should use such syntax but as you see it works (I found it in some docs in Google)
1

That is because is sending the array with a "data" , is the same as the jquery ajax, the Input::all() is showing [data]='_token=d76as78d6as87d6a&data1=value1 etc... not as a sincronized request if you print values Input::all will show you a complete array, laravel handle a different way the POST requests sent by jQuery

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.