Ajax call returns internal 500 error - c#

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

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

Your WebMethod must be static
[WebMethod(true)]
public static ActionResult DeleteBook(int bookId)
{
bookRepository.DeleteBook(bookId);
return RedirectToAction("Books", "ProductManager");
}

Add HttpPost to your method and try
[HttpPost]
public ActionResult DeleteBook(int bookId)
{
bookRepository.DeleteBook(bookId);
return RedirectToAction("Books", "ProductManager");
}

Related

Ajax Post not finding method in page model

I have the following method inside my page model which is called Order
public async Task<IActionResult> OnPostAddRecord(string recordId)
{
return new JsonResult("Hello");
}
My Ajax code to call said method:
$('#RecordList').change(function () {
var formData = {
recordId: $("#RecordList").val(),
};
$.ajax({
type: 'POST',
data: formData,
url: '#Url.Page("order", "addrecord")',
success: function (result) {
alert(result)
},
error: function (result) { }
});
});
Yet when it's fired it returns StatusCode 400, however, I have another Ajax method on the same page that works successfully, the difference is that one is a GET whereas this is a POST.
I really can't see what the problem is here.
You need to include the request verification token in your FormData: https://www.mikesdotnetting.com/article/336/ajax-posts-in-razor-pages-and-http-400-errors

Unable to parse JSON returned by JQuery ajax call

I am calling a method using JQuery ajax given below
$.post('../User/GetCountry',
{
zone: 1
},
function (data) {
alert(data);
alert(data["Countries"]);
}, "json").fail(function (jqXHR, textStatus, errorThrown) {
//alert(textStatus);
});
C# code
public static string GetCountry()
{
var result = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Countries.GetAll());
return result;
}
Now when I debug my code on server side i see the below result which is perfect json according to me
[{"Id":4,"Name":"France"},{"Id":3,"Name":"Germany"}]
But in javascript I am getting the json as
[[object Object],[object Object]]
Can anyone please let me know what I am missing here
SOLVED USING
var jsonData = JSON.stringify(data);
var jsonParse = JSON.parse(jsonData);
There's a few issues with your code. First, despite the fact that you're passing a parameter zone to the web service method the method itself doesn't receive this parameter. Second, if you want to return JSON don't use the return type string. Use JSONResult. This will allow you to remove the static keyword as well. I'd recommend changing your method like so:
public JSONResult GetCountry(int? zone)
{
// ...
}
There are two final changes you should make. The first is to use ASP.Net MVC's built in Json() method to handle serialization of your object. The second is that you should always project your data layer results even if they happen to already be in the structure you want to use. This way if you change your data layer object in a way that breaks the service you'll get a compile error instead of a run time exception.
return Json(from c in Countries.GetAll() select new { Id = c.Id, Name = c.Name })
I'd also recommend avoiding using $.get or $.post as they abstract away settings that can be useful when access web services. If you want to shorthand it I'd recommend wrapping the $.ajax call in your own function. You're also going to want to think about standardizing your web service responses. Your web service is a protocol of sorts and as such it benefits from having a well defined header. For a more in-depth explanation take a look here: Introduction to MVC Service Based Web Applications
try this :
alert(data[0].Name)
$.ajax({
type: 'POST',
url: '../User/GetCountry',
data: {
zone: 1
},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
works good for me. You need to make sure you're sending a content-type of "application/json", preferably using the Json() helper method in Controller.
Solved this after searching bit more
$.post('../User/GetCountry',
{
zone: 1
},
function (data) {
var jsonData = JSON.stringify(data);
var jsonParse = JSON.parse(jsonData);
}, "json").fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
Try using JSON.parse():
$.post('../User/GetCountry',
{
zone: 1
},
function (data) {
data=JSON.parse(data)
alert(data["Countries"][0].Name);
}, "json").fail(function (jqXHR, textStatus, errorThrown) {
//alert(textStatus);
});

Null parameters doing HTTP POST from Ajax to Web API

I've read several StackOverflow posts about this and corrected my code several times
but I cant get my webAPI post method to work. I'm trying to receive a post parameter
but it comes always null.
What I am trying to do is receiving a base64 string that represents a canvas that is
creating with jquery when the user clicks the button:
function MakePhoto(ctrl) {
html2canvas(ctrl, {
onrendered: function (canvas) {
var canvasData = canvas.toDataURL()
jQuery.ajax({
url: "../api/webinfo",
type: "POST",
data: { imagedata: canvasData },
success: function () {
alert("success");
},
error: function () {
alert("failure");
}
});
}
});
}
my WebInfoController.cs looks like this:
public void Post([FromBody]string imagedata)
{
}
imagedata parameter comes always NULL
And this are the headers I am receiving at webapi:
"Method: POST,
RequestUri: 'http://myhost/RestFulApi/api/webinfo'
Content: System.Net.Http.StreamContent
User-Agent: Chrome/27.0.1453.94
Content-Length: 42226
Content-Type: application/x-www-form-urlencoded; charset=UTF-8}
I hope you could help me.
Thanks
OK, I found the problem after some hours researching. I had to pass the data parameter to ajax function using:
"=" + canvasdata, without the parameter name:
jQuery.ajax({
url: "../api/webinfo",
type: "POST",
data: "=" + canvasData,
success: function (response) {
alert(response);
},
error: function (response) {
alert(response.responseText);
}
});

$.getJSON is not calling call back function

call back in not being called.
function GetTrainingResults(id,callback){
$.getJSON("/dashboard/GetTrainingResults/", {'id':id}, callback);
}
GetTrainingResults('id',function(result){
alert(result);
});
and code behind is
public ActionResult GetTrainingResults(int id)
{
string test = "You are there.";
return Json(test, JsonRequestBehavior.AllowGet);
}
Or suggest and another way. Task in to call controller method and wait for method response in javascript.
Thanks
If you use jQuery.ajax, you'll at least be able to see the error being returned by the server:
function getTrainingResults(id, callback) {
$.ajax({
url: "/dashboard/GetTrainingResults/",
data: {id: id},
success: function(data) {
callback(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
callback(errorThrown);
}
});
}
id in your Action method takes an int, yet you're passing it a string of 'id' in your JS. Either change your JS or you action method so that the types match.
Check that your request is returning successfully, the ajax shorthand functions only call the callback if the request is successful (ie status code 200 and of the right data type, ie json). Try the full .ajax jquery function and see whats going on under the hood.
.getJSON() is equivient too
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
so it might be hitting error: due to the data type.
Source http://api.jquery.com/jQuery.getJSON/

jQuery $.ajax success not firing from JsonResult

My code makes an ajax call:
$.ajax({
url: "/Controller/EmailUserKeys",
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
It calls an action in my controller which returns some JSON:
public JsonResult EmailUserKeys(string UserId)
{
...
return Json(new { success = true });
}
My problem is that the ajax error function is called and not the ajax success function.
Why?
PS. If my action returns "return null;", the ajax success function is called.
You must allow GET which is disabled by default when returning JSON results:
public JsonResult EmailUserKeys(string UserId)
{
...
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
or use a POST request:
$.ajax({
url: "/Controller/EmailUserKeys",
type: "POST",
dataType: 'json',
data: { userId: 'some user id' },
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
Also never hardcode the url to your controller action as you did. Always use url helpers when dealing with urls in an ASP.NET MVC application:
url: "#Url.Action("EmailUserKeys", "Controller")",
And here's a piece of advice: use a javascript debugging tool such as FireBug if you are doing any web development. Among with other useful things it allows you to inspect AJAX requests. If you had used it you would have seen the response sent from the server which would have looked like this:
This request has been blocked because sensitive information could be
disclosed to third party web sites when this is used in a GET request.
To allow GET requests, set JsonRequestBehavior to AllowGet.
And you wouldn't need to come to StackOverflow and ask this question as you would have already known the answer.
You should edit your code to this:
public JsonResult EmailUserKeys(string UserId)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
See the official documentation for more info:
http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior.aspx
The reason for disabling this by default is because of JSON hijacking. More information about this can be found here:
http://haacked.com/archive/2009/06/25/json-hijacking.aspx
Hope this helps you out!

Categories