JQuery Ajax Success not being triggered - javascript

I'm not sure why my ajax success isn't being triggered/called.
My controller is called and the code is executed fine. I'm not returning anything, so my method is a void! Do I need to return something (ActionResult/JSonResult/etc) to get the success to trigger?
Here is my controller code.
public void DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
}
Here is my ajax call.
$.ajax({
url: '/ManageSpaces/DeleteEvent',
dataType: 'json',
data: {
eventId: eventId,
},
success: function() {
//var obj = JSON.parse(doc);
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}
});

Yes, you need to return JsonResult:
[HttpPost]
public JsonResult DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
return Json("{status:"OK"}");
}
Since you are changing back-end data, set it to POST:
$.ajax({
url: '/ManageSpaces/DeleteEvent',
method: 'POST',
dataType: 'json',
data: {
eventId: eventId,
},
success: function(response) {
if(response.status=="OK"){
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}else{
console.log("Error occured")
}
}
});

Related

How to send a JavaScript object on the server side (ASP NET MVC)?

Below is the relevant code (JS+jQuery on the client side):
function getuser(username, password) {
var user = new Object();
user.constructor();
user.username = username;
user.password = password;
//....
$("#a1").click(function () {
var u = getuser($("#username").val(), $("#password").val());
if (u == false) {
alert("error");
} else {
//....
}
});
}
The question is how to send var u to a session on the server side?
You can use ajax to accomplish this. Something like:
$.ajax({
url: "/Controller/Action/",
data: {
u: u
},
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
//handle response from server
}
});
Then have a controller action to receive the data:
[HttpPost]
public ActionResult Action(string u)
{
try
{
//do work
}
catch (Exception ex)
{
//handle exceptions
}
}
Note that /controller/action will be specific to where youre posting the data to in your project
See the documentation
For example:
If you just want to do a simple post the following may suit your needs:
var user = getUser(username, password);
$.post(yourserverurl, user, function(response){console.log("iam a response from the server")});
As the documentation says:
This is a shorthand to the equivalent Ajax function:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So In your example:
$.ajax({
type: "POST",
url: "/mycontroller/myaction",
data: {user: getUser(username, password)},
success: function(responseFromServer){//handleResponseHere},
error: function(xhr){//handleyourerrorsHere}
dataType: yourdatatype
});

Passing values from controller to view

Controller
public ActionResult Booklist(string bookid) {
return View();
}
View
// other codes
url: 'Index/Booklist',
method: 'POST',
success: function (a) {
var windows = window.open('Index/Booklist');
}
But it seem to invoke dispose(); twice..the reason being the first time it calls return View(); and the second var windows = window.open('Admin/GenerateQRCode');
I need to pass data from controller to javascript in sencha and also pass them to the View..is this possible?
Try this:
public ActionResult Booklist([DataSourceRequest] DataSourceRequest request,string bookid)
{
//result should be your data.
var result=0;
return Json(result, JsonRequestBehavior.AllowGet);
}
// other codes
url: 'Index/Booklist',
method: 'POST',
data:{
'bookid': bookid
},
success: function (result) {
}
Please try this.. Sorry earlier one is not working...
$.ajax({
url: "#Url.Action("Booklist", "Home")",
data: {
'bookid': bookid
},
dataType: 'json',
async: true,
type: 'POST',
success: function (response) {
}
});
public ActionResult Booklist( string bookid)
{
var result=1;
return Json(result, JsonRequestBehavior.AllowGet);
}
This is work for me...

Ajax success function not fired

I have a javascript function with a ajax call. It reaches safely to the controller with no problem. But when the controller give back the result into json format, then I have not get the data in view page.
Below the code snippets:
Controller Action Method:
public JsonResult GetContactDetails(string contactId)
{
Contact objContact = _contactService.Get(contactId.TryToInt());
return Json( objContact, JsonRequestBehavior.AllowGet);
}
Javascript Method:
function GetContactDetails(contactId, designation, mobile) {
$.ajax({
cache: false,
url: '#Url.Action("GetContactDetails", "Clients")',
type: "GET",
async: false,
data: {contactId:contactId},
dataType: 'json',
success: function (result) {
alert("Yes");
debugger;
},
error: function () {
alert("error");
}
});
}

Calling a controller method via javascript

I have an ASP.NET application where I am invoking a controller methode from JavaScript. My JavaScript code looks like this:
function OnNodeClick(s, e) {
$.ajax({
type: "POST",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (data) {
if (data != null) {
$('#GridView').html(data);
}
},
error: function (e) {
alert(e.responseText);
}
});
}
This calls the Home controller's DeviceManifests() method.
This is what the method looks like:
public ActionResult DeviceManifests(Guid selectedRepo)
{
var repoItem = mock.GetRepoItem(selectedRepo);
return View("Delete", repoItem.childs);
}
The method gets invoked but the problem is the Delete-View doesn't get rendered. There's no error, just nothing happens.
How can I update my code to get my desired behaviour?
Do like below code so if you have error you will have it in alert box or success result will rendered in DOM
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
dataType: "html",
success: function (data) {
if (data != null) {
$('#someElement').html(data);
}
}
},
error: function (e) {
alert(e.responseText);
}
});
You can do the redirect in the javascript side.
function OnNodeClick(s, e) {
$.ajax({
type: "GET ",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (msg)
{
window.location = msg.newLoc;
}
});
}
Make sure you include the redirect url in action and return JsonResult and not ActionResult. I'd also include pass the guid so that the destination Action and let it look up the data.

Do you need to use two calls - 1 get and 1 post in ajax or can you send data back with the success / failure?

I have the following controller method:
public JsonResult CreateGroup(String GroupName)
{
ApplicationUser user;
var userName = User.Identity.Name;
using (DAL.GDContext context = new DAL.GDContext())
{
user = context.Users.FirstOrDefault(u => u.UserName == userName);
if (user != null)
{
var group = new Group();
group.GroupName = GroupName;
group.Members.Add(user);
context.Groups.Add(group);
context.SaveChanges();
}
}
string result = userName;
return Json(result, JsonRequestBehavior.AllowGet);
}
with the following ajax call:
$(function () {
$('#CreateGroup').on("click", function () {
var groupName = $('#groupname').val();
if (groupName != '') {
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: JSON.stringify({ 'GroupName': groupName }),
dataType: "json",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
}
});
The CreateGroup function fails saying "Uncaught ReferenceError: data is not defined"
Do i have to use another Json request - type post - to get the username?
you can do the call without using JSON.stringify. Also your controller method has a cache attribute that may yield more control. Personally, I would use the controller cache control. You are probably getting a cached version of the controller call prior to returning data.
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult CreateGroup(string GroupName)
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: { 'GroupName': groupName },
dataType: "json",
traditional: true,
success: function (data, status, xhr ) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
NOTE: Update success callback.

Categories