Calling controller method (ASP MVC3) method from ajax doesn't work - ajax

I am using the following syntax to make a call to controller method from ASP page.
$.ajax({
url: 'ControllerName/MethodName',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify({ param: param1}),
success: function () {
alert("Success!!!");
},
error: function () {
alert("Failed!!!");
}
});
I have two ASP pages (views), both having same controller. If I call above method from first page, controller method gets called successfully. But if call same method from second page I get alert message "Failed". Also I tried using GET type, tried with other controller methods and all. Nothing will be called from second view. can anyone help me what can be problem? I am new to MVC.

Since your ajax is expecting result of JSON data from your Controller method do you have return Json(data, JsonRequestBehavior.AllowGet)?

Try change content type to:
contentType: 'application/json; charset=utf-8'
or/and specify url using mvc helper like:
url: #Url.Action("action"),
Works in my example. Hope it will help.

Related

How to pass controller action in Jquery AJAX Call in Oxid eSHOP

I am working on Jquery AJAX in OXID eSHOP.
I want to pass proper action (function) name in AJAX url parameter.
Below is my code:
jQuery.ajax({
type: "POST",
data: {
variable: value
},
url: "",
success: function(data) {
}
});
I want to call one function in url parameter.
But don't know how to pass its value in url paramaeter.
Anyone knows then please help me.
You should include function name as URL parameter, just like the shop does it in most situations:
http://your-shop.com/index.php?cl=controller&fnc=functionname

Jquery ajax call will not reach succes function

Pulling out my hair. Countless hours trying to get ajax call to work...
Jquery:
function doAjaxPost(episode_id) {
alert("cc");
$.ajax({
type: "POST",
url: "http://localhost:8080/yay/episodes/remove",
data: JSON.stringify({
episode_id : episode_id
}),
dataType: 'json',
contentType: "application/json",
success: function(){
alert("o");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.error(errorThrown);
}
});
};
Controller:
#RequestMapping(value = "/episodes/remove", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.OK)
public void removeEpisodeFromList(#RequestBody String episode_id) {
System.out.println("Episode_id : " + episode_id);
}
And I call the function from:
MARK AS WATCHED
It reaches the controller where the correct thing is printed out.
But then FireBug just says "SyntaxError {}" and success function alert is never called.
It probably won't affect the data being passed in, but you really don't need the JSON.stringify action on your data parameter. See http://api.jquery.com/jQuery.ajax/#example-0
Also, if you are trying to get JSON back from your spring MVC controller, you need to use the #ResponseBody annotation. This will instruct Spring to not try to render out the template. I actually wrote a blog post about getting JSON back from a spring MVC application a little while back that may help.
The section titled "Mapping the response body with the #ResponseBody annotation" here can give you more information
Also, the success() function is depreciated. The done() function should be used now. More information on that can be seen at the jquery url above.
Hope this helps!
http://benashby.com/spring/response-body-annotation

Calling ASP.NET MVC 4 Controller from Javascript

I'm calling an ASP.NET MVC 4 control method from Javascript (in a cshtml file) using $.ajax() as shown below
$.ajax({
url: '#Url.Action("MyAction", "MyController")',
type: 'GET',
data: { 'id': "123"},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
}
});
The controller action method is
public JsonResult MyAction(string id)
{
// Do stuff
return new JsonResult();
}
which is getting called ok but is causing a GET 500 (Internal Server Error).
I don't really care about the returned data I just want to call the controller method to update a model.
Can anyone let me know why I'm getting the 500 or an alternative way of doing this that would be great.
For security reasons you cannot use the GET method in ajax requests (See JSON Hijacking).
You just have to do it like this:
return Json(data, JsonRequestBehavior.AllowGet)
or better off, change the method to post
type: 'POST',

Unexpected GET request after POST on AJAX call to MVC Action

I have an action method that is invoked with POST method over AJAX. Method looks like this:
[HttpPost]
public ActionResult Save(MyModel model)
{
/// do something and save
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
What happens is that after this method is call by the $.ajax, from unknown reason follow up GET request is made to same controller and same action. This call is not made anywhere and it's probably implemented either in browser or in ASP.NET MVC as Post/Redirect/Get pattern which I don't need in this case.
Is there a way to disable this programmatically because GET counterpart of Save method is not implemented and server returns 404 with HTML contents in it.
EDIT, this is the client-side AJAX script:
function saveDonkey(donkey) {
var jsonData = JSON.stringify(donkey);
$.ajax({
url: "/Donkey/Save",
data: jsonData,
contentType: "application/json",
dataType: "json",
type: "POST",
success: function () {
fetchPage(); /// This just issues GET request to another predefined method
}
});
}

Making Asynchronous calls in ASP.Net MVC 3

I'm using $.ajax asynchronously to send some json to a controller marked with [HttpPost], like this:
$.ajax({
url: location.href,
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: theJson,
async: true,
});
This works fine, but the method expects an ActionResult, I guess with a new view. But I don't want that - I just want to do a little update on the server without updating the page.
Is there any way to set up a method on the server to do the update, independent of the view?
You should change the method to return void.

Resources