aleczandru aleczandru - 5 months ago 25
Javascript Question

Ajax call returns internal 500 error

Hi I am trying to execute an ajax call to the server but I seem to have no luck I keep getting back on the console an error 500 Internal server error.This is my ajax call:

$("body").on("click", "#ok", function (e) {
var id = $(this).attr("data-bookid");
$.ajax({
url: "/ProductEditor/DeleteBook",
type:"POST",
data: { bookId: parseInt(id) },
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
e.preventDefault();
})


And this is the C# code I am trying to call:

public ActionResult DeleteBook(int bookId)
{
bookRepository.DeleteBook(bookId);
return RedirectToAction("Books", "ProductManager");
}


While trying to debug I have noticed that the DeleteBook method is not even called.

What am I doing wrong?

EDIT I have added the [HttpPost] attribute but it still does not work

Answer

Without more information, it's not easy to tell you what you are doing wrong.

However, the error function callback for the jQuery ajax function takes three parameters:

(jqXHR, textStatus, errorThrown)

$.ajax({
    url: "/ProductEditor/DeleteBook",
    type:"POST",
    data: { bookId: parseInt(id) },
    success: function (data) {
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});

The third parameter, errorThrown will have the HTTP response text for the call to /ProductEditor/DeleteBook. I would suggest looking at what errorThrown is showing, as well as possibly running the entire program in debug mode.

Perhaps var id = $(this).attr("data-bookid"); is incorrect, and the value of id is being set to undefined?

Also, you can use the Network tab in the F12 Development Tools in IE or Chrome, Firebug in Firefox, or Fiddler to debug ajax calls. You can watch the ajax request being sent to the server as well as the response from the server in order to see whether the correct data (bookId) is being sent in the correct format (JSON) and what the response is from the server