Laravel 5.4 not able to parse FormData javascript object sent using Jquery Ajax

*爱你&永不变心* 提交于 2019-12-12 04:32:55

问题


Lately I've been trying to solve an issue with no luck, basically I'm trying to submit a form to the server using AJAX, the form has files, so I'm using the FormData javascript object in JQuery 1.12. The data arrives to the server but in I way I don't know how to format it.

This is my AJAX function:

function saveMenu(id){
    var formElement = document.getElementById("menu-form");
    var formData = new FormData(formElement);
    formData.append('_method', 'PUT');
    $( "#form-wrapper" ).toggleClass( "be-loading-active" );
    $.ajax({
        type: 'PUT',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: "{{url('myUrl')}}",
        data: formData,
        enctype: 'multipart/form-data',
        processData: false,
        success: function(response) {
            toastr.success('Yai! Saved successfully!')
        },
        error: function(response) {
            toastr.error('Oh oh! Something went really wrong!')
        },
        complete: function() {
            $( "#form-wrapper" ).toggleClass( "be-loading-active" )
        }
    });
}

and when I perform a dd($request->all()); in my controller I get something like this:

array:1 [
  "------WebKitFormBoundaryRCIAg1VylATQGx46\r\nContent-Disposition:_form-data;_name" => """
    "_token"\r\n
    \r\n
    jtv4bnn8WQnP3eqmKZV3xWka2YOpnNc1pgrIfk0D\r\n
    ------WebKitFormBoundaryRCIAg1VylATQGx46\r\n
    Content-Disposition: form-data; name="blocks[43][title]"\r\n
    \r\n
...

Things I've tried:

  • Set the HTTP verb to POST. Same result.
  • Set the AJAX contentType: false, contentType: application/json. Empty response.
  • Remove enctype: 'multipart/form-data'. Same response.

Any help is appreciated.


回答1:


I've been trying to debug that for 2 hours and i found out that method PUT is not working with formData properly.

Try changing

type : "PUT" 

into

method : "POST"

Then change your method on your backend from put to post and you'll see the difference. I used below codes to test it

$("#menu-form").submit(function (){
    var fd = new FormData();
    fd.append('section', 'general');
    fd.append('action', 'previewImg');
    fd.append('new_image', $('.new_image')[0].files[0]); 
    $.ajax({
        method : 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token()}}'
        },
        url: "{{url('upload-now')}}",
        data : fd,
        contentType: false,
        processData: false,
        success: function(response) {
            console.log(response);
        },
    });
    return false;
});

And in my controller

public function test(Request $request){
    dd($request->all());
}

Ill try to research more about this issue.




回答2:


Finally I gave up trying to make it work and tried a more vanilla approach, I still don't know the reason why the request is formated like that, but the XMLHttpRequest() function works perfectly and the migration is not a big deal.

The equivalent of the function I posted about would be:

function saveMenu(action){
    var formElement = document.getElementById("menu-form");
    var formData = new FormData(formElement);
    formData.append('_token', $('meta[name="csrf-token"]').attr('content'));

    var request = new XMLHttpRequest();
    request.open("POST", "{{url('myUrl')}}");
    request.send(formData);

    request.onload = function(oEvent) {
      if (request.status == 200) {
        toastr.success('Yai! Saved successfully!');
      } else {
        toastr.error('Oh oh! Something went really wrong!');
      }
      $( "#form-wrapper" ).toggleClass( "be-loading-active" );
    };
}



回答3:


This fixed it for me

data: form_data,
contentType: false,
processData: false,

processData: false prevents jQuery from parsing the data and throwing an Illegal Invocation error. JQuery does this when it encounters a file in the form and can not convert it to string (serialize it).

contentType: false prevents ajax sending the content type header. The content type header make Laravel handel the FormData Object as some serialized string.

setting both to false made it work for me. I hope this helps.

$('#my-form').submit(function(e) {
        e.preventDefault();
        var api_token = $('meta[name="api-token"]').attr('content');
        form_data = new FormData(this);
        $.ajax({
            type: 'POST',
            url: '/api/v1/item/add',
            headers: {
                Authorization: 'Bearer ' + api_token
            },
            data: form_data,
            contentType: false,
            processData: false,
            success: function(result,status,xhr) {
                console.log(result);
            },
            error: function(xhr, status, error) {
                console.log(xhr.responseText);
            }
        });
    });

also remember to use $request->all(); $request->input() excludes the files



来源:https://stackoverflow.com/questions/45503814/laravel-5-4-not-able-to-parse-formdata-javascript-object-sent-using-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!