asp.net mvc ajax call not calling controller after publishing on server - javascript

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">

Related

Make an ajax call from JavaScript to C# controller in a different folder

Update Note at the bottom of question
I am having issues making an AJAX call from JavaScript to the C# Controller. I am pretty sure that my issue is the connection url of my AJAX call on the javascript file. If the connection url is not the issue, then I think it might be something in my C# controller. I know jQuery is loaded properly since I was able to console log information before the AJAX call in the RunDemo function.
Here is an explanation of what I am trying to accomplish:
I have a simple html page with one button. On button click, I need to make an ajax call to my c# controller and retrieve a string. On AJAX success I would then alert on the html page to the user the messages retrieved from the C# controller. Here is a picture of my "TheDemo" repository:
Here is my "Index" html page:
<!DOCTYPE html>
<html>
<head>
<title>The Demo</title>
<script type="text/javascript" src="../Scripts/jquery-3.6.min.js"></script>
<script type="text/javascript" src="../Scripts/demo.js"></script>
</head>
<body>
<div class="demo-container">
<h1>Demo</h1>
<button type="button" id="SubmitButton">Submit</button>
</div>
</body>
</html>
Here is the "demo.js" javascript file:
//Function makes an ajax to the controller
function RunDemo(){
$.ajax({
url: '/Demo/RunDemo',
type: 'POST',
dataType: 'json',
success: function (retData)
{
console.log(retData);
alert(retData.Message);
},
error: function (retData)
{
console.log(retData);
}
});
}
//Event handles the "Submit" button
$(document).on("click", "#SubmitButton", function () {
RunDemo()
});
Here is the "DemoController.cs" C# file:
using System;
class DemoController : Controller
{
[HttpPost]
public JsonResult RunDemo()
{
object obj = new { Message = "Return From Controller" };
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
Here is an image of my error in the Google Chrome console:
UPDATE:
I have fixed the ajax connection url. It still does not work, I have updated the image of the Google Chrome console.
UPDATE 2:
It has been brought to my attention that it could be the way I am opening the file. At the moment, I am opening the html page with Google Chrome inspector. I am not "running" a process in Visual Studio code. Do I need to host the C# Controller in something?
Thanks!
Your AJAX URL is relative to your HTML file, which is itself on your local disk. Therefore, it is not going to your controller, which is running on localhost presumably, but is going to file:///Demo/RunDemo as per the error message.
AJAX requests are better debugged via the Network tab of your browser development tools.
tl;dr -- Invoke your page via the URL as hosted by your ASP.NET app. It should be along the lines of http://localhost/View/index.html.
The url you specified for ajax call is not correct. in ASP.NET mvc we specify just the controller name without the controller postfix and the format of the url also not correct. try the following for url:
url: '/Demo/RunDemo'
Fix your ajax file
$.ajax({
url: '/Demo/RunDemo',
type: 'POST',
success: function (retData)
{
console.log(retData);
alert(retData.Message);
},
error: function (retData)
{
console.log(retData);
}
});
Well, your problem is not with the AJAX call but with the CORS permission at the back-end for the security of the system with cross origin resource sharing. you see even though it's allow resource on same URL but your browser blocks the all the resources from different URL.
using System;
using System.Web.Http.Cors;
class DemoController : Controller
{
[EnableCors(origins: "http://yourlocalhost:", headers: "*", methods: "*")]
[HttpPost]
public JsonResult RunDemo()
{
object obj = new { Message = "Return From Controller" };
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
Try to look into this document if above code does not help:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

JavaScript skipping over AJAX Post

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

Fail to send html content to webservice gives error not found

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.

problem CasperJS POST via AJAX not working

I'm working on a scraper of my bank statements with CasperJS, so far I've managed to login and get to the statements page. I accomplished to get the table with the first page of the statement, but I need to get it complete.
The bank's web have the option to export to a .txt file (sort of a CSV actually), but in order to download it I have to be able to download the file that comes as an attachment in the response header of a POST request when I submit a form by clicking a button.
So I figured that I could do the POST via AJAX, get the response and output it. I tried running the code on the firebug console and it works, but for some reason it just doesn't work in CasperJS.
Btw, I have tried using --web-security=no , still doesn't work
This is how I'm trying to do it:
this.then(function() {
eurl = "http://bankurl.com";
response = this.evaluate(function() {
params = $("#lForm").serialize();
$.ajax({
type: "POST",
url: eurl,
data: params,
success: function (data) {
return data.responseText;
},
error: function (xhr,status,error){
return error;
}
});
});
this.echo(response);
});
I wasn't able to test this with the code you provided, but it looks as though you just aren't returning anything back from the evaluate().
return __utils__.sendAJAX(url, 'POST', params);
You would probably also need to call CasperJS with the following:
casperjs --ignore-ssl-errors=true /path/to/script.js
Well, after struggling finding a way to solve this I finally did, I just put the ajax call inside a try catch and found that the error was that it wasn't reading the eurl variable (I declared it outside the evaluate). I put it inside and it worked. Thanks for your help

Error when calling webservice with jquery

I have read a lot about jquery and i have a webservice where i convert a companyID to the real companyName. Now i want to call that webservice with jquery or javascript. The webservice is on host http://webservice/service.asmx en i'm working on http://tlmos. I don't work and i always get an error
Here is my code:
<script type="text/javascript" src="http://kmosvi24/_layouts/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var test = "KBEACDNV";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://webservice/service.asmx/getCompanyByCompanyID",
data: "{'sCompanyID:' + 'test'}",
dataType: "json",
succes:function(response){ alert("good"); },
error: function(response) { alert("Uh oh"); },
complete: function(response) { alert("" + response); }
});
</script>
Can someone help me?
thx
Umm.. you spelled success wrong on line 11
.. and you probably want to format your data as
data: "sCompanyID=test"
Take a quick pass through the jQuery API page on this one to verify you are passing the parameters that your service expects. It looks like you are expecting a SOAP packet with an ASMX service, and jQuery is more suited to hitting a restful service generated from an ASHX file or WCF service.
You can make a request to a different server, but only if the call uses GET. Since all you do is lookup anyway, a GET request should be fine.
As some othe people have pointed out you cannot call a webservice on another domain, however as you are using ASP.NET, you can write a raw HTTP handler (normally with an .ashx extension to proxy your request from client to server.) Which you'd place on your "timos" server
so in your ashx file you can write something along the lines of...
public void ProcessRequest (HttpContext context)
{
XmlDocument wsResponse = new XmlDocument();
string url = "http://webservice/service.asmx/getCompanyByCompanyID?CompanyID="
context.Request.Form["CompanyID"].ToString()
wsResponse.Load(url);
string XMLDocument = wsResponse.InnerXml;
context.Response.ContentType = "text/xml";
context.Response.Write(XMLDocument);
}
Hope this helps.
You can't do AJAX calls to hosts other than your own. If you really have to do this make a call to your own server and use a simple proxy to redirect to the domain you need.
You could do this for example by using a ProxyPass-directive in your webserver:
ProxyPass /service/ http://webservice/service.asmx
ProxyPassReverse /service/ http://webservice/service.asmx
Then you can issue an AJAX-request to /service/getCompanyByCompanyID and it will be proxied to the correct URL.
I don't think you are using the data parameter right, usually it's a key-value pair like:
data: {sCompanyID: 'test'}
I believe that they way you are using it will result in jQuery attempting to post to http://webservice/service.asmx/getCompanyByCompanyID?sCompanyID:blah
Also aren't .NET web services SOAP? I don't think jQuery can parse that...
edit: Nevermind, didn't realize you were passing these as json data. Thanks commenters!
In order to run your web-services from Jquery, you should use either WCF or just usual web services, but you should add [ScriptMethod] to your service's method and [ScriptService] to your webservice description.
Wow wow
just noticed that you're trying to call the service from one host to another... that one won't work. service should be hosted on the same domain as the page where it's being called from.
as a reply to Jeff's answer, correct way to format data is data: {key: "value"}
With jQuery Ajax Requests you need to use the following format when defining the variables to be sent in the request:
data: "variableName=variableContent",
You wrote:
data: "{'sCompanyID:' + 'test'}"
This won't work for two reasons:
- You have included curly brackets which don't need to be there.
- You have used a semi-colon,":", instead of an equals sign,"=".
So long as you change these it should work.
P.S I only just realized that Jeff Fritz has already given you the right answer. His answer is spot on!

Categories