jQuery: why does $.post does a GET instead of a POST - asp.net-mvc

I'm trying to do an ajax call and populate the "Data" div with the results of the ajax call,
but i get an error saying: "Server Error in '/' Application. The resource cannot be found. Description: HTTP 404. Requested URL: /Home/GetStuff"
When I look with Firebug the request was a GET to /Home/GetStuff and the answer was 404 Not found. Why I doesn't do a POST as I required in the ajax call? How can I do a POST?
I tried using $.post and got the same behavior, though I haven't checked the jquery code, I assume $.post is a wrapper around $.ajax.
Also i tried Ajax.ActionLink and it works fine, though I would like to use jQuery and not the Microsoft's ajax js libraries.
The code follows:
Home/TestStuff.aspx
function aClick() {
$.ajax({
type: "POST",
url: $("#MeFwd").href,
data: ({ accesscode: 102, fname: "JOHN", page: 0 }),
dataType: "html",
success: renderData
});
};
function renderData(data) {
$("#Data").html(data.get_data());
}
<div id="Data">
</div>
<div id="link">
Click Me!
</div>
HomeController.cs
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetStuff(int accessCode, string fName, int? page)
{
return "<table><tr><td>Hello World!</td></tr></table>";
}

Change your onclick="aClick" to onclick="aClick(); return false;". Clicking the link is doing a get to the url instead of running your JS.

$('#MeFwd').click(function() {
$.ajax({
type: "POST",
url: $("#MeFwd").href,
data: ({ accesscode: 102, fname: "JOHN", page: 0 }),
dataType: "html",
success: function(data){
$("#Data").html(data);
});
});
};
I don't think you can call a function on your return ... but I could be wrong.
Or look into load:
http://docs.jquery.com/Ajax/load#urldatacallback

Related

Rails 6: AJAX data not reaching controller

I'm trying to make a pretty standard ajax call, this is my code:
// app/javascripts/packs/contacts.js
jQuery(() => {
$(".upload-contacts-button").on("click", (e) => {
e.preventDefault();
//...
$.ajax({
url: "/pre-parse-contacts",
type: "post",
data: { my_param: random_param },
success() {},
});
});
});
This is my route:
post 'pre-parse-contacts', to: 'contacts#pre_parse_contacts', as: 'pre_parse_contacts'
For some reason the data I send in the ajax request never reaches the controller, when I try to puts params in the controller action I get this result:
------- DEBUG --------
{"controller"=>"contacts", "action"=>"pre_parse_contacts"}
I'm sure the ajax call is made, even the js.erb view tries to render but I get errors due to I need the data I send in the ajax call. Why is this happening?
Sorry I found the answer to my issue, it seems I was trying to send an array of strings in the params of the ajax request, this is why it was never reaching the controller.
joining the array made the trick:
$.ajax({
url: "/pre-parse-contacts",
type: "post",
data: { my_param: random_param.join() },
success() {},
});

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)?

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