简体   繁体   中英

Ajax request throws 500 error, but the request works

I setup an API controller to handle an ajax request. Every time the Ajax request is made from the script below I get a 500 error:

POST http://localhost:58463/api/Reservations 500 (Internal Server Error) jquery-2.1.0.min.js:4
l.cors.a.crossDomain.send jquery-2.1.0.min.js:4
o.extend.ajax jquery-2.1.0.min.js:4
(anonymous function) Confirm?spaceNumber=5:129
o.event.dispatch jquery-2.1.0.min.js:3
r.handle

but the weird thing is - the request actually succeeds. It creates a reservation. How is that possible, and how can I resolve the error?

View:

@model *********.Models.Reservation
@section Scripts {
   $(document).ready(function () {
        console.log('ready');
        $('#confirmationForm').submit(function (event) {
            event.preventDefault();
            var $form = $(this);
            $.ajax({
                type: $form.prop('method'),
                url: $form.prop('action'),
                data: $form.serialize(),
                dataType: "json",
                traditional: true,
                success: function (response) {
                    console.log('yes!');
                }, 
                error: function(response) {
                    console.log('no');
                }
            });
        });
    });
}

<div class="section about" style="height: 100%;">
    <div id="main-content" class="main-content">
        <div class="container">
            <div class="section-heading">
                <h2 class="red">Confirm Your Reservation</h2><br />
            </div>
            <div class="section-content">
                <div class="row">
                    <div class="hero-buttons text-center">
                        <a href="#" class="btn btn-gray btn-lg white">No</a>
                        <form action="/api/Reservations" method="post" id="confirmationForm">
                            @Html.Hidden("UserName", @Model.UserName)
                            @Html.Hidden("SpaceNumber", @Model.SpaceNumber)
                            <input type="submit" value="Yes" class="btn btn-red btn-lg white">
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

APIController:

public class ReservationsController : ApiController
{
    private MyContext db = new MyContext();

    // POST api/Reservations
    public HttpResponseMessage PostReservation(Reservation reservation)
    {
        if (ModelState.IsValid)
        {
            reservation.Game = db.Games.FirstOrDefault(g => g.ID == AppSettings.CurrentGameID);
            db.Reservations.Add(reservation);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, reservation);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = reservation.ID }));
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }
}

Solution

heymega pointed me in the right direction by telling me to look further into the 500 error I was receiving. Using FireBug I found this in the exception message:

"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."

I was able to remedy this by adding these lines to me WebApiConfig.cs file

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

You are specifying the return data type as JSON

 dataType: "json"

jQuery is trying to parse the response to JSON and since it can't, it thinks the request was unsuccessful.

If you remove the dataType then jQuery will try and work it out itself and it should fix your issue.

Hope this helps

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