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!
Related
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
I have the following ajax call in my view:
var obj = { maintId: id };
$.ajax({
url: '#Url.Action("EditLog" ,"Maintenance")',
type: "GET",
dataType: "json",
data: obj,
async: false,
success: function (data) {
alert(data.Reason);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
alert(status);
alert(error);
}
});
It hits the Action (EditLog) just fine but not able to return the values for SystemID and Reason to the ajax call success data area.
Note that I will be putting values from the DB but for testing, I put hard coded values for SystemID and Reason. When I run the code it goes to the error: function section and I get a parsererror. I am wondering if I am doing anything wrong.
[HttpGet]
public ActionResult EditLog(int maintId)
{
return Json(new { SystemID = 1233, Reason = "ReagDegree change" });
}
You need to use the JsonRequestBehavior.AllowGet as well:
return Json(new { SystemID = 1233, Reason = "ReagDegree change" }, JsonRequestBehavior.AllowGet);
The JsonRequestBehavior Enum:
Specifies whether HTTP GET requests from the client are allowed.
Which by default is set to Deny get.
https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.jsonrequestbehavior?view=aspnet-mvc-5.2
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/
I need to submit a simple form and validate the model. If the model is valid, I would like to serialize that model and send it via POST to an external (https) web service using custom headers. Finally I would handle the response that I get back from the request and display the appropriate message.
I am validating the model from the controller perfectly and serialize the object but can't seem to find a way to create a JSON post request to the external URI. Is there a way to do this using JQuery.ajax or $.post. Maybe I am missing a key ajax param to achieve this.
Thanks
So based on the clarification on the question this is what you can do:
Define the controller method that will validate the object
public ActionResult TestMethod() {
// do server-side validation
return Json(aValidObject);
}
You do an ajax post to your controller so you can validate your model then get back a json result.
$.ajax({
url: '#Url.Action("TestMethod")',
data: some_data,
type: "post",
success: function (result) {
// result is a valid json object
doExternalPost(result);
}
});
Add custom header and do the external post
function doExternalPost(o) {
$.ajax({
url: 'http://some_external_url',
data: o,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader('custom_header', 'some_value');
},
success: function() {
// post is sucessful
},
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText || xhr.responseText;
alert('An error has occured: ' + errorMessage);
},
});
}
try this
var data = {jsonDataObjectHere};
var request = $.ajax({
url : 'externalUrl.com/something.whatever',
type : 'POST',
data : data // see above
});
request.success(function(response){
// the response is the stuff from the server
});
i'm sleepy so forgive typos
good luck
EDIT: for a bit of clarification, with MVC you really dont need to serialize the json object, mvc will accept it as it is.
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");
}