0

I can add the data to the database correctly, but Ajax success function is not working. I always get the error function :

View:

<div id="dvform">
    <!-- some data-->
    <input type="submit" value="submit" id="btnsubmit" />
</div>

<script>
        $(document).ready(function () {
            $("#btnsubmit").click(function () {
                addAppointment();
            });
        });
            function addAppointment (){
                $.ajax({
                    type: 'POST',
                    url: '/FuelerAppointments/Create',
                    contentType: 'application/json; charset=utf-8',
                    dataType: "html",
                    data: $("dvform").val(),

                    success: function (data) {
                      swal("Done!", "The appointment was saved successfully!", "success");
                    },
                    error: function (data) {

                         swal("Error deleting!", "Please try again", "error");
                     },
                });
            }

Controller :

[HttpPost]
public ActionResult Create(FuelerAppointment fuelerAppointment)
{
    return Json(fuelerAppointment, JsonRequestBehavior.AllowGet);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ms.Fatima
  • 123
  • 1
  • 13

2 Answers2

0

First you should change dataType: "html", to dataType: "json", and create FuelerAppointment object before the $.ajax():

        var fuelerAppointment = {};  
        fuelerAppointment.Name = $("#Name").val(); 

and then the data in ajax method

data: '{fuelerAppointment: ' + JSON.stringify(fuelerAppointment) + '}',

For more information check this link Using AJAX In ASP.NET MVC

Marwen Jaffel
  • 703
  • 1
  • 6
  • 14
0

change dataType: "html" to dataType: "json"


and in data properties should you write like this

var model = {
     prop1: prop1Value,
     prop2: prop2Value,
     ...
};
data: {fuelerAppointment: model}

Or


data: JSON.stringify({
   fuelerAppointment: {
        prop1: prop1Value,
        prop2: prop2Value,
        ...
   }
})

Notes: the fuelerAppointment object should behave a sem proprieties in C# class

Mahmod Abu Jehad
  • 167
  • 2
  • 14