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.
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">
I am sending an AJAX POST request using jQuery on a chrome extension but the data doesn't arrive as expected, accented characters turn out malformed.
The text "HÄGERSTEN" becomes "HÄGERSTEN".
The text appears fine in the console etc, only via AJAX to this other page it appears as mentioned. My AJAX call is basic, I send a data-object via jQuery $.ajax. I've tried both with and without contentType, UTF-8 and ISO-8859-1. No difference.
This is how I make my AJAX call:
var newValues = {name: 'HÄGERSTEN'}
$.ajax({
url: POST_URL,
type: 'POST',
data: newValues,
success: function() ...
});
The newValues object has more values but I retrieve them from a form. However, I have tried to specify these values manually as newValues['name'] = 'ÄÄÄÄ'; and still would cause the same problem.
The original form element of the page that I am sending the AJAX to contains attribute accept-charset="iso-8859-1". Maybe this matters.
The target website is using Servlet/2.5 JSP/2.1. Just incase it might make a difference.
I assume this is an encoding issue and as I've understood it should be because Chrome extensions require the script files to be UTF-8 encoded which probably conflicts with the website the plugin is running on and the target AJAX page (same website) which is using an ISO-8859-1 encoding, however I have no idea how to deal with it. I have tried several methods of decoding/encoding it to and from UTF-8 to ISO-8859-1 and other tricks with no success.
I have tried using encodeURIComponent on my values which only makes them show that way exactly on the form that displays the values I have sent via POST, as e.g. H%C3%84GERSTEN.
I have no access to the websites server and cannot tell you whether this is a problem from their side, however I would not suppose so.
UPDATE
Now I have understood POST data must be sent as UTF-8! So a conversion is not the issue?
Seems like the data is UTF-8 encoded when it is sent and not properly decoded on the server side. It has to be decoded on the server side. Test it out with the following encode and decode functions:
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
var encoded_string = encode_utf8("HÄGERSTEN");
var decoded_string = decode_utf8(encoded_string);
document.getElementById("encoded").innerText = encoded_string;
document.getElementById("decoded").innerText = decoded_string;
<div>
Encoded string: <span id="encoded"></span>
</div>
<div>
Decoded string: <span id="decoded"></span>
</div>
We too faced the same situation but in our case we always sent the parameters using JSON.stringify.
For this you have to make changes, 1) While making call to the page via AJAX you have to add content-type tag defining in which encoding data is sent
$.ajax
({
type: "POST",
url: POST_URL,
dataType: 'json',//In our case the datatype is JSON
contentType: "application/json; charset=utf-8",
data: JSON.stringify(newValues),//I always use parameters to be sent in JSON format
EDIT
After reading your question more clearly I came to know that your server side JSP uses ISO-8859-1 encoding and reading some posts, I came to know that all POST method data will be transmitted using UTF-8 as mentioned.
POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard
But while reading post jquery-ignores-encoding-iso-8859-1 there was a workaround posted by iappwebdev which might be useful and help you,
$.ajax({
url: '...',
contentType: 'Content-type: text/plain; charset=iso-8859-1',
// This is the imporant part!!!
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
}
});
Above code is taken from Code Posted by iappwebdev
I don't know if it could have been solved using POST-data and AJAX. Perhaps if I made a pure JavaScript XHR AJAX call, I might be able to send POST-data encoded the way I like. I have no idea.
However, in my desperation I tried my final option (or what seemed like it); send the request as GET-data. I was lucky and the target page accepted GET-data.
Obviously the problem still persisted as I was sending data the same way, being UTF-8 encoded. So instead of sending the data as an object I parsed the data into a URL friendly string with my own function using escape, making sure they are ISO-8859-1 friendly (as encodeURIComponent encodes the URI as UTF-8 while escape encodes strings making them compatible with ISO-8859-1).
The simple function that cured my headaches:
function URLEncodeISO(values) {
var params = [];
for(var k in values) params[params.length] = escape(k) + '=' + escape(values[k]);
return params.join('&');
}
The client side character coding is not completely up to you (immagine the usage of the page from different users all around the world: chinese, italian...) while on the server side you need to handle the coding for your purposes.
So, the data in the Ajax-POST can continue to be UTF8-encoded, but in your server side you coan to do the following:
PHP:
$name = utf8_decode($_POST['name']);
JSP:
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
I have a form on a remote server, consisting of just a text box and a submit button. Once this form is submitted (PHP) XML is returned. How can I go about using ajax/jQuery to fill out this form, submit it, and receive the XML to process?
Untested, I think you should be heading somewhere in the direction of the following JS. Ofcourse, this is light thinking, there could be all kind of implications with the following (eg. XSS protection etc..). But if we're talking a simple, plain form, I think this could work.
Also, expanding the following with some failure fallbacks etc would be good practice. For documentation on the Ajax function, check the API docs.
// This should be the URL where your <form> action's value is pointing at
var url = 'http://remote/form/action';
// The textfield's data you want to submit
var textFieldValue = 'foobar';
$.ajax(
url,
{
'type': 'POST', // Could also be GET, depending on your form
'data': {
'textFieldName': textFieldValue,
},
'success': function (data) {
console.log(data); // Your raw XML in a string
}
}
);
Edit: As Kevin B mentioned, you'll be heading into cross-domain policy problems with the above, making this situation that more complex. Therefor you should need to make sure you have CORS arranged on the targeted domain. See Wikipedia CORS for more info.
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!
I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.
I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.
Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.
Here's an except from MVC RC1 release notes - Jan 2009
IsMvcAjaxRequest Renamed to IsAjaxRequest
The IsMvcAjaxRequest method been
renamed to IsAjaxRequest. As part of
this change, the IsAjaxRequest method
was updated to recognize the
X-Requested-With HTTP header. This is
a well known header sent by the major
JavaScript libraries such as
Prototype.js, jQuery, and Dojo.
The ASP.NET AJAX helpers were updated to send this header in
requests. However, they continue to
also send it in the body of the form
post in order to work around the issue
of firewalls that strip unknown
headers.
In other words - it was specifically renamed to be more 'compatible' with other libraries.
In addition, for anyone who hasnt read the full release notes but has been using previous versions - even as recent as the beta - I STRONGLY recommend you read them in full. It will save you time in future and most likely excite you with some of the new features. Its quite surprising how much new stuff is in there.
Important note: You will need to make sure you upgrade the .js file for MicrosoftAjax.MVC (not the exact name) if upgrading to RC1 from the Beta - otherwise this method won't work. It isn't listed in the release notes as a required task for upgrading so don't forget to.
See Simons answer below. The method I describe here is no longer needed in the latest version of ASP.NET MVC.
The way the IsMvcAjaxRequest extension method currently works is that it checks Request["__MVCASYNCPOST"] == "true", and it only works when the method is a HTTP POST request.
If you are making HTTP POST requests throug jQuery you could dynamically insert the __MVCASYNCPOST value into your request and then you could take advantage of the IsMvcAjaxRequest extension method.
Here is a link to the source of the IsMvcAjaxRequest extension method for your convenience.
Alternatively, you could create a clone of the IsMvcAjaxRequest extension method called
IsjQueryAjaxRequest that checks Request["__JQUERYASYNCPOST"] == "true" and you could dynamically insert that value into the HTTP POST.
Update
I decided to go ahead and give this a shot here is what I came up with.
Extension Method
public static class HttpRequestBaseExtensions
{
public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
{
if (request == null)
throw new ArgumentNullException("request");
return request["__JQUERYASYNCPOST"] == "true";
}
}
Checking from an action if a method is a jQuery $.ajax() request:
if (Request.IsjQueryAjaxRequest())
//some code here
JavaScript
$('form input[type=submit]').click(function(evt) {
//intercept submit button and use AJAX instead
evt.preventDefault();
$.ajax(
{
type: "POST",
url: "<%= Url.Action("Create") %>",
dataType: "json",
data: { "__JQUERYASYNCPOST": "true" },
success: function(data) {alert(':)');},
error: function(res, textStatus, errorThrown) {alert(':(');}
}
);
});
Why don't you simply check the "X-Requested-With" HTTP header sent automatically by most Javascript libraries (like jQuery) ?
It has the value 'XMLHttpRequest' when a GET or POST request is sent.
In order to test it you should just need to check the "Request.Headers" NameValueCollection in your action, that is :
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
return Json(...);
else
return View();
This way, you can simply differentiate regular browser requests from Ajax requests.
Ok, I have taken this one step farther and modified my jQuery file to load the additional parameter into the post data, so I don't have to repeat the "__JQUERYASYNCPOST: true" for every call to post. For anybody that's interested, here's what my new definition for $.post looks like:
post: function(url, data, callback, type) {
var postIdentifier = {};
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
else {
postIdentifier = { __JQUERYASYNCPOST: true };
jQuery.extend(data, postIdentifier);
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
}
I added the "postIdentifier" variable as well as the call to jQuery.extend. Now the Helper explained in spoon16's response works without having to add any thing special to my page-level jQuery code.