简体   繁体   中英

Ajax form submit with file in Laravel 5

I am trying to implement fileupload in laravel 5. But firstly want to send data, for example, simple string. My form:

    {!!Form::open(["url"=>"/photos", "method" => "post", "files"=>true, "onsubmit"=>"send();return false;"])!!}    
    {!!Form::text("title", null, ["class"=>"form-control"])!!}    
    {!!Form::submit("Send", ["class"=>"btn btn-primary", "id" => "submitForm"])!!}    
    {!!Form::close()!!} 

My send function

function send() {
    var formData = new FormData(this);
    $.ajax({        url: "/photos",
                    method: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    cache: false,
                    success: function(data) {
                        console.log(data);
                    },
                    error: function(data) {                   
                    }
                });
}

My route:

Route::post("/photos", "PhotosController@store");

My store function

public function store()
{
    $data = \Illuminate\Support\Facades\Request::all();
    return $data;
}

And I have an empty data! Via Formdata is nothing receiving, but if I change params from formData to {text: "Hola"}, so I see that in answer from server, but via text I cant upload photos in future. What am I doing wrong ? Why I receive empty formdata ? Thanks

Since I got here with the same problem and found a solution I thought I'd post it here.

First of all you will have to use var formData = $(this).serializeArray(); to get your form data, instead of var formData = new FormData(this); .

According to the documention Laravel will automatically return a HTTP response with 422 status code including a JSON representation of the validation errors.

full ajax call:

//#ajax-form is the id of your form.
$("#ajax-form").submit(function(e)
    {
        var postData = $(this).serializeArray();
        var formURL = $(this).attr("action");

        $.ajax(
            {
                url : formURL,
                type: "POST",
                data : postData,
                success:function(data)
                {
                    console.log(data);
                    //data: return data from server
                },
                error: function(data)
                {
                    console.log(data.responseJSON);
                    //in the responseJSON you get the form validation back.
                }
            });
        e.preventDefault(); //STOP default action
        e.unbind(); //unbind. to stop multiple form submit.
});

if you want to upload files through AJAX I suggest you read this . Hope this helps!

Happy coding :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM