I have a JavaScript function that triggers on a button click, but the Chrome Developer Tools skips over the AJAX Post. A 500 Error occurs, but break points inside the Controller are never hit, so none of the variables appears to be passing. I've seen many JavaScript questions on this site, but couldn't find one that addressed this situation. Here's what my code looks like and thanks in advance!
JavaScript:
$("#calculate").click(function () {
var $indicator = $("#Indicator");
$.ajax({
type: "POST", //THIS IS NEVER HIT, JUST SKIPPED OVER!
url: '#Url.Action("LogPrices", "Sales")',
data: {
indicator: $indicator.val(), iD: $("#ID").val()
},
success: function (data) {
// logic
}
});
});
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogPrices(bool indicator, long iD)
{
// logic
return Json(priceLog, JsonRequestBehavior.AllowGet);
}
Remove
[ValidateAntiForgeryToken]
this mechanism is used for some security measures, if you want to use it, read about it
bascially you have to send the token to the controller, other wise it's going to give an error because the security measure failed - no token given-
you can just add this
#Html.AntiForgeryToken()
and then submit it as a form, MVC will automatically take care of this and validates the token for you
EDIT:
missing one of the parameters of your controller action might cause 500 as well, in your case the ID and the indicator should both be sent, make sure your html is retrieving the values correctly
usually I start tracking the error by making static values
Related
this is for the first time I am having a problem like this,
my code is running smoothly on my localhost, but i am getting the error of bad request after uploading the same code on my server,
the following is the error I am getting,
http://URL/Controller/Method 400 (Bad Request)
here is my code
Controller:
[Interceptors.AccountFilter]
[HttpGet]
public ActionResult method(string city, int bookmark)
Javascript:
$.ajax({
type: "GET",
url: "/controller/method",
data: {
city: city,
bookmark: bookmarks
},
})
what can be the possible issue that i am getting,
PS:
the code is running on localhost properly
change your code from url: "/controller/method" to url:'#Url.Action("method","controller")'
Try taking off the first '/' so your url will become: "controller/method".
I would also put a piece of code in the first line of the method to check that the address is correct and is triggering.
You can also try temporarily commenting out the two lines below. They aren't needed for testing and looking at the first attribute would probably stop your request.
[Interceptors.AccountFilter]
[HttpGet]
(I can't comment) Please change the "customErrors" tag on web.config so you can see the error details
<customErrors mode="Off">
In an ASP.NET MVC project, I have a controller method that accepts POST requests, like so (with the "User" class for completeness):
[HttpPost]
public ActionResult TestMethod(User user)
{
return Content("It worked");
}
public class User
{
public string Name { get; set; }
public string Email { get; set; }
}
I call this method with jQuery Ajax:
$.ajax({
url: '/test/TestMethod/',
data: JSON.stringify({ user: { name: 'NewUserName', email: 'username#email.com' } }),
type: 'POST',
success: function (data) {
alert(data);
},
error: function (xhr) {
alert('error');
}
});
When I create a fresh ASP.NET MVC project, and include this code in a new Test controller, everything works fine. Viewed through Fiddler, a single POST request is made, and I get the controller method return value back.
However, when I run this code in the current MVC project that I'm developing, it doesn't work. From Fiddler I see that the ajax call first initiates a POST method, that gets a 301 http status error ("moved permanently"?). Immeditely afterwards a GET request is made, which generates a 404 not found error (which makes sense as there is no GET action method with this name available).
So I use the exact same code, in a fresh projects and in the existing project, but the code only works in the fresh project. So clearly there's something about my existing project that somehow prevents this from running properly (and causes the odd behaviour of generating both a POST and a GET request). But I have no idea what it could be, so any suggestions welcome...!
Update - routing information:
public static void RegisterRoutes(RouteCollection routes)
{
routes.AppendTrailingSlash = true;
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
Update 2:
Looks like this issue is caused by Content Security Policy settings that were switched on for this project.
You need to put the [FromBody] annotation before your method's argument.
[HttpPost]
public ActionResult TestMethod([FromBody]User user)
{
return Content("It worked");
}
ASP.net MVC framework will use the arguments you pass in the body to recognize the method.
I ran into this issue after I implemented Custom Errors, and My form was posting a File back to the server tthat was larger than the Max Allowed. This resulted in a 404.13 error... I guess that is the default error for "file too large"
When custom errors were turned on all I saw was the 404. It was driving me crazy that I was getting a 404 error when I knew that the request type was a post, and the url where it was posting was correct.
Hope this helps someone.
I am getting 'Request-URI Too Large' error when I tried to call a rails controller function from javascript with a large json parameter. I'm using Webrick http server. Is there any way to resolve this without changing the server?
I have something like:
$.ajax({
url: 'application/get_list',
data: { options : options_json, selected_option : selected_option_string},
success: function(data) {
// Insert the data to a div (returned data is a select tag with options)
},
type: 'get'
});
The simplest fix would be to change it to a POST request, and set up the action to handle that, and then you won't run into this error.
If you need to it to be a GET request, you can add a file called webrick.rb to the config\initializers directory with this content:
if defined?(WEBrick::HTTPRequest)
WEBrick::HTTPRequest.const_set("MAX_URI_LENGTH", 10240)
end
and if you keep getting the error, keep increasing the number 10240 until it works.
Since your comment says it needs to be a GET request, you really have no option but to set the MAX_URI_LENGTH. From the WEBrick source:
if #request_line.bytesize >= MAX_URI_LENGTH and #request_line[-1, 1] != LF
raise HTTPStatus::RequestURITooLarge
end
If you need really long URI's, then set it to something absurd, like 9223372036854775807
I am trying to send html content as a string to a webservice but failing with an error not found although the same call works if i send a simple string like "test".
Webservice Code:
public string List(DateTime showdate, string viewtype, int timezone, string test)
{
------ whatever ------
}
Javascript Code:
var showdate = "22/05/2014",
viewtype = "rest",
timezone = 2,
test = $("body").html(); // if i change to something like: test = "My name is Inigo Montoya" it works fine.
$.ajax({
type: option.method,
url: option.url,
data: {"showdate": showdate, "viewtype": viewtype, "timezone": timezone, "test": test},
success: function(data){ //--- whatever --- },
error: function(data){ //--- whatever --- }
});
You can open the chrome inspector on your code testing page, and directly paste the above javascript code to see what kind of error is returned.
I can think of 2 problems now:
Over-lengthy URL
The jQuery code that you used to fire the ajax call should be fine, but those 2 params type and data can leads to the problem.
For example, if $("body").html() is over 2000 characters and the request method is set as GET, the ajax call won't work because the URL will be too long to be understood by the browser.
Given that you mentioned
if i change to something like: test = "My name is Inigo Montoya" it works fine.
I believe the possiblility of this issue is quite high.
Cross-domain ajax
If the target location is a foreign domain, they can potential deny the access by your AJAX call.
Same as above, it is highly recommended to check this problem via Chrome inspector for this issue.
Try this, as you tagged under webservices and json, Hope this should work for you,
var data={"showdate": showdate, "viewtype": viewtype, "timezone": timezone, "test": test};
var jsonData= JSON.stringify(data);
$.ajax({
type: option.method,
url: option.url,
data: jsonData,
success: function(data){ //--- whatever --- },
error: function(data){ //--- whatever --- }
});
I believe you may be hitting ASP's built-in request validation which is used to prevent XSS (Cross-site-scripting).
By default, posting a field which contains HTML can cause it reject a request.
Request validation is a feature in ASP.NET that examines an HTTP request and determines whether it contains potentially dangerous content. In this context, potentially dangerous content is any HTML markup or JavaScript code in the body, header, query string, or cookies of the request. ASP.NET performs this check because markup or code in the URL query string, cookies, or posted form values might have been added for malicious purposes.
Have a look at this MSDN page for more information.
Note that it is possible to disable request validation for a single field instead of doing it site-wide...
(taken from this Stack Overflow question)
On a controller action:
[ValidateInput(false)]
ActionResult SomeAction(string validationIgnored){...}
or a specific model property:
[AllowHtml]
string SomeProperty {get; set;}
Note thst this protection is here for a reason, and if you disable it, you're accepting responsibility for validating the input yourself. Have a look at this blog post by Rick Strahl for some suggestions and alternatives.
I am using ckeditor in our project. passing that value in ajax post like
//$form is -> $('form') jquery object
$("#ajaxsubmitbutton").on('click', function () {
CKupdate();
$.ajax({
type: ($form.attr('method').toLowerCase() == 'post' ? 'POST' : 'GET'),
url: ($form.attr('action') == 'undefined' ? window.location : $form.attr('action')),
data: $form.serialize(),
success: function (data) {
// Use local eval, since it will work in this context
callbackFunction(data);
},
error: function () {
var data = "ajaxerror";
callbackFunction(data);
}
});
});
Ckeditor update code :
function CKupdate(){
for ( instance in CKEDITOR.instances )
CKEDITOR.instances[instance].updateElement();
}
$form.serialize having below value :
"Id=0&Title=dfg&ShortText=rer&CultureCode=en-US&StartDate=3%2F12%2F2014&EndDate=3%2F26%2F2014&Text=%3Cp%3Etest3%3C%2Fp%3E%0D%0A"
controller code :
public JsonResult Save(int id, string title, string shortText, string text, DateTime? startDate, DateTime? endDate, string cultureCode)
{
//process some operation
}
it throws some ajax error like " 500 -internal server not found". i don't know what is the real cause for this issue
may be the problem in serializing the form. any help on this.
I suspect that the tags are the issue here-
Assuming Asp.net MVC here you have two options-
Decorate your model property with the [AllowHtml] method (not sure how much of a pain it would be to convert your properties to a model here)
Put the [ValidateInput(false)] tag on your controller method
You may need to add the following tag to system.web in your config as well
<httpRuntime requestValidationMode="2.0"/>
You may also run into issues if your submit isn't a post in which case you'll want to add allowget to your return value.
Not sure if this is your issue without the full error but that is where I'd start. You may want to check the response in fiddler or firebug to see if you can get more information on that exception.
Hope that helps.