Home > Back-end >  Why I'm getting empty request when i post data to the controller using ajax in laravel
Why I'm getting empty request when i post data to the controller using ajax in laravel

Time:12-08

Hello guys i'm trying to post data to the controller using ajax in laravel but it is giving me empty request in the controller although the data i'm sending is already showing when i do console.log(name)

This is my form

<form action="" method="POST">
 <div >
  <div >
<label >Permission Name</label>
  <input type="text" id="name" name="name"  placeholder=" Enter a Permission name">
  </div>
  </div>
 <div >
 <button type="button"  data-bs-dismiss="modal">Close</button>
 <button type="button"  data-bs-dismiss="modal">Submit</button>
 </div>
</form>

And this is the ajax code

<script>
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $(document).on('click', '.add_per', function (e) {
            e.preventDefault();

            var name = $('#name').val();
            console.log(name)
            $.ajax({
                type: 'post',
                enctype: 'multipart/form-data',
                url: "{{route('admin.permissions.store')}}",
                data: {
                    name:name
                },
                processData: false,
                contentType: false,
                cache: false,
                success: function (data) {
                    if (data.status === true) {
                        $('#success_msg').show();

                    }
                },
                error: function (reject) {
                    alert("Error occurred !");
                }
            });
        });
    </script>

CodePudding user response:

processData: false,

You told jQuery not to process the object you pass to data so it isn't being encoded in a way that allows it to be sent in the HTTP request.

contentType: false,

You also told it not to set the content-type to the format it encoded the data to (which doesn't make a difference given the above, but would if you fixed the first problem).

enctype: 'multipart/form-data',

jQuery doesn't accept an enctype property on the options object, but if it did it would be a for contentType. multipart/form-data is an encoding generally used for requests that include files; jQuery can't encode data using that format.

  • Related