Ajax success function not fired - javascript

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");
}
});
}

Related

C# How to call MVC Controller function by using javascript or jquery

I have this at my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteUser(UserViewModel viewModel)
{
}
I have this at my cshtml:
<input type="button" id="btnDelete" value="Delete" />
I have this at my js file:
$('#btnDelete').click(function (e) {
});
How do I call controller function from js file?
$.post("Controller/CreateUser", dataToPost)
.done(function(response, status, jqxhr){
// this is the "success" callback
})
.fail(function(jqxhr, status, error){
// this is the ""error"" callback
});
or
var data = {
username: $('#username').val().trim(),
password: $('#password').val()
};
$.ajax({
type: "POST",
url: "Controller/CreateUser",
content: "application/json;",
dataType: "json",
data: JSON.stringify(data),
success: function(d) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
ps: compose the data object according to the UserViewModel properties.
Inside the button click, execute ajax request
$('#btnDelete').click(function (e) {
$.ajax({
type: "POST",
url: 'controller/DeleteUser',
dataType: "json",
success: function(data){
//html content
},
});
}
It's very easy to access any controller method using ajax post method.
As here I'm getting states as per selected country using
'RegionesController' method name 'GetStates' also here I'm passing
CountryId to get states as per this id.
EX:
function GetStates() {
$.ajax({
type: "POST",
async: false,
url: abp.appPath + 'Regiones/GetStates?CountryId=' + $("#ddlCountry").val(),
success: function (result) {
//return data or object
},
error: function (err) {
abp.notify.info(err.statusText);
}
});
}

JQuery Ajax Success not being triggered

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")
}
}
});

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.

Ajax post not calling the success from Chrome browser works in IE

I have a add button it calls the controller does what it needs to do but it never calls the success function from the chrome browser? Works in IE so I know it is getting called with another browser not sure why chrome is not working?
$('#ui_btn_AddItem').click(function () {
//...getting the data values here....
$.ajax({
url: "/userGroup/CopyItem",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { "id": distribId, "selectedIDs": selectedValues },
success: function (data) {
alert('success');
window.location(data.retUrl); // Success Callback
},
error: function (req, status, error) {
alert('error');
bootbox.alert(req.responseText);
}// error: errorCallback
});
});
My controller is called like [HttpPost]
public ActionResult CopyItem(
...doing some copy stuff then returning the json result.
return Json(new { success = true, retUrl = returnUrl }, JsonRequestBehavior.AllowGet);
not sure why my alert doesn't come up with chrome any ideas?

ajax post not working without alert message

i have a problem with ajax post function. Ajax function doesn't working without alert message. If add alert message, div content will be refresh and working my code.
I have a mv3 application. And post form data to this javascript function. Like that:
function Add_Definition() {
var data = $.extend({ call: "Add_Definition", url: "/Definition/Definition", type: "post", dataType: "html", data: $("#definition_form").serialize() }, data);
Load(ajaxrequest(data));
}
function Load(val) {
if (val == true) {
var data = $.extend({ call: "Load", render: $("#render"), url: '#Url.Action("Definition", "Definition")', type: "get", dataType: "html", data: { "groupid": '#Request.QueryString["groupid"].ToString()'} }, data);
ajaxrequest(data);
}
}
My ajax javascript function is below.
function ajaxrequest(param) {
var result = true;
//alert("hi there");
$.ajax({
type: param.type,
url: param.url,
data: param.data,
dataType: param.dataType,
success: function (result) {
$(param.render).empty();
$(param.render).html(result);
result = true;
},
error: function (request, status, error) {
result= false;
}
});
return result; }
If remove // char from javascript code, it will not work, (need refresh page), if have a alert message, content will be refresh with load function.
How is error?
you can also direct call like
var divElem = $('#yourdivid').load('#Url.Action("Definition", "Definition")');

Categories