0

In this I have a form and some attributes with id(level,state,photocard).I am using ajax call to send form data like this, and level,state attribute are successfully going to backend as they have,input type="text".But photocard whose, input type="file" is not going to backend.What changes should I make in this code?

<script>
            $(document).ready(function(){
                $("#submit_btn").click(function(){
                    alert("success");
                    $.ajax({
                        url:"/WeatherApi/UserDetailsController",
                        type:"post",
                        data: {
                            level: $('#level').val(),
                            state: $('#state').val(),
                            photo_card: $('#photo_card').val(),
                            },
                        sucess:function(response)
                        {
                            alert(response.status);
                        }
                    
                    });
                });
            });
        </script>
  • https://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload It may help you – Rova Ram Aug 05 '21 at 07:07

1 Answers1

0

To send files you have to set the enctype for your ajax call to multipart/formdata.

You also have to send your data using a FormData object.

So using your code (not tested but should get you going):

<script>
    var data = new FormData();

        data.append('level', $('#level').val());
        data.append('state', $('#state').val());
        data.append('photo_card', $('#photo_card')[0].files[0]);

            $(document).ready(function(){
                $("#submit_btn").click(function(){
                    alert("success");
                    $.ajax({
                        url:"/WeatherApi/UserDetailsController",
                        type:"post",
                        enctype: 'multipart/form-data',
                        data: data,
                        sucess:function(response)
                        {
                            alert(response.status);
                        }
                    
                    });
                });
            });
        </script>
Gijs Beijer
  • 560
  • 5
  • 19