jQuery ajax GET fails - post

I have the following jQuery ajax request in a .js file:
$.ajax({
type: "GET",
url: "Download.aspx/ZipCheck",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
The request fails and an alert pops up that says "200 OK". However, if I change the ajax request type to "POST" then it works and I have an alert that pops up with the expected data being returned from Download.aspx/ZipCheck.
Why does the GET fail, and why does the POST succeed? My understanding must be flawed about the difference between the two, because I thought that a GET request still would return something from the server.

WebMethods are by default restricted to POST, you need to explicitly enable the GET request, for example using UseHttpGet on the ScriptAttribute, like this:
[WebMethod, ScriptMethod(UseHttpGet=true)]
public thing ZipCheck() {
//return object
}

Related

How to send JSON to MVC API (using Ajax Post)

I am trying to post some data using Ajax, but it is not getting through when using content type of application/json (HTTP/1.1 406 Not Acceptable), however if I change the content type to 'application/x-www-form-urlencoded' then it does work.
Any ideas?
Ajax code extract:
$.ajax({
type: "POST",
data: {"hello":"test"},
url: "http://workingUrl/controller",
contentType : 'application/json',
cache: false,
dataType: "json",
.....
Web API 2:
public IHttpActionResult Post(testModel hello)
{
/// do something here
}
Model:
public class testModel
{
public string hello {get;set;}
public testModel()
{ }
}
Fiddler:
HTTP/1.1 406 Not Acceptable (In the IDE, I have a breakpoint in the Post method which is not hit).
I have tried adding a formatter to WebAPi.config, but no luck
config.Formatters.Add(new JsonMediaTypeFormatter());
Try with this JSON.stringify(TestData) as shown below -
var TestData = {
"hello": "test"
};
$.ajax({
type: "POST",
url: "/api/values",
data: JSON.stringify(TestData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Output -
I've never specified contentType when I've done this and it's always works. However, if it works when you use 'application/x-www-form-urlencoded' then what's the problem?
I do see a couple thing off in your ajax. I would do this
$.ajax({
type: "POST",
data: {hello:"test"},
url: "http://workingUrl/controller/Post",
cache: false)}
For data, maybe quotes around the variable name will work but I've never had them there.
Next, the url in the ajax call doesn't have the name of your controller action. That needs to be in there.

Getting HTTP 405 Method not allowed error when calling Web API method from JQuery

I have the following method in my Web API controller
[HttpGet]
[ActionName("GetByModule")]
public Object Get([FromUri]int id)
{
//var dblayer = new Db(WebConfigurationManager.ConnectionStrings["ConnectionString"]);
var annDb = new ContactsDB(WebConfigurationManager.ConnectionStrings["ConnectionString"]);
return annDb.GetContacts(id).Tables[0];
}
Here i the Jquery code which i am using to call the method
$.ajax({
type: "GET",
contentType: "application/json",
url: link,
data: null,
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, err) {
alert("Error");
}
});
The URL which is getting called is
http://localhost:56834/api/Contacts/GetByModule?id=9
But i keep getting HTTP 405 Method Not Allowed on calling it from Jquery.
Any idea what i may be doing wrong.
Thanks in Advance
Can you make sure you are making a "GET" request? (maybe from Fiddler or browser's debug mode). I say this because you seem to setting the "contentType" property in your jquery, which ideally should not be present as you should not be sending body in a "GET" request. Could you share your full raw request(may be from Fiddler)?

AJAX call to MVC controller action

I am new to MVC programming.I am working on a simple POC application that displays/edits data from Database.
I have 2 views and 2 controllers. On one of them the JQuery AJAX call to MVC controller action method is working fine. But not on the other one (In here, the AJAX call is not triggering the Action method).
Can anyone had this situation before???
The JQuery code is below:
$('#ddlZones').change(function () {
var value = $('#ddlZones option:selected').val();
// alert(value); var status = $('#ddlStatus option:selected').val();
// alert(status); $('#lstResources').children().remove();
$('#lstBeds').children().remove();
$.ajax({ url: 'FillResources', type: 'POST',
data: JSON.stringify({ ZoneId: value }),
dataType: 'json', contentType: 'application/json',
success: function (result) {
for (var r in result) {
$('#lstResources').append('<option value="' + result[r].Value + '">' + result[r].Text + '</option>');
}
}
});
});
Thanks
Latha
Check the controller url is called or not,
Also in data parameter you can call it simply like { ZoneId: value } instead of
JSON.stringify({ ZoneId: value }),
At server side get this parameter by using $_POST if you are using PHP
in controller, also check in console that, you are getting json from server side or not.
$.ajax({ url: 'FillResources', type: 'POST',
data:{ ZoneId: value },
dataType: 'json', contentType: 'application/json',
success: function (result) {
for (var r in result) {
$('#lstResources').append('<option value="' + result[r].Value + '">' + result[r].Text + '</option>');
}
}
});
Please check the request and the response in the browser. You can use the inbuilt ones in IE/Chrome/FF(Firebug) or fiddler. It probably is just a routing issue if this is ASP.NET MVC.
Specifically, look for what your request url is and what is the HTTP response from the server.
It is always a good practice to specify both the controller and actions in the routing urls to avoid any such errors.
Another thing to check will be if the change function is actually being called? You can put a console.log before the ajax request to make sure that this is not the case.

Simple problem on jQuery ajax method

I am trying to simply use jQuery's ajax method and method only call error callback.
$('form').submit(function() {
$.ajax({
url: this.action,
data: $(this).serialize(),
type: 'POST',
dataType: 'html',
success: function() {
debugger
alert('alert');
},
error: function(xhr, status, error) {
//status value is "error".
}
});
});
I am requesting to ASP.NET MVC action method. Method get request as expected and return partial view without any problem. Then jquery call error callback without specify detailed error info. I want to know some details about error then i can decide what can cause it.
Edit : I have tested below code and it works without problem. I just canceled form submit event.
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: this.action,
data: $(this).serialize(),
type: 'POST',
dataType: 'html',
success: function() {
debugger
alert('alert');
},
error: function(xhr, status, error) {
//status value is "error".
}
});
});
Still answer is expecting right answer who can tell me reason of this error.
Could it be the reference this.action is undefined? Look at the network tab of your favorite dom inspector or just the error console of firebug. Does the POST request look as expected? (Check the URL, data sent, error code, etc)
$(this).attr('action') will certainly work, assuming this points to the form.

Request URL encoding issue in $.ajax call and Max request URL length in $.ajax as compared to Ajax.ActionLink

I am doing a simple $.ajax request:
$.ajax({
type: "POST",
url: "/Run/" + param1 + "/" + param2,
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
If my param2 value is like http://localhost/pub/file?val1=Some Text&val2=Some Text then encoding done using escape(param2), encodeURI(param2), encodeURIComponent(param2) doesn't help. And I get following ERROR -->
HTTP Error 400.0 - Bad Request
ASP.NET detected invalid characters in the URL
My Questions -->
How should I encode param2 ?
What is the maximum length of request URL in $.ajax call ?
Is request URL max length dependent on type of browser from which request is made ?
I have observed that if I use Ajax.ActionLink then I do not need to encode the parameters passed to action and I can pass parameters with length > 10,000 characters as well. But I do not know how to make an explicit call using Ajax.ActionLink from my java script. I need to click on that actionlink to make call through Ajax.ActionLink.
Benefits of Ajax.actionLink-->
Please see the length of parameter categoryName passed to action using Ajax.ActionLink (This is mine observation)
Such big parameters should be posted and not sent in the URL.
$.ajax({
type: 'POST',
url: '/Run',
data: { param1: param1, param2: param2 },
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
This will automatically handle parameter encoding. If you absolutely insist on sending them in the url you may declare a global javascript variable that will hold the url to call:
<script type="text/javascript">
var url = '<%= Url.Action("Run"), new { param1 = "value1", param2 = "value2" } %>';
$(function() {
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
});
</script>

Resources