I'm not able to make ajax call to the controller action method which returns the json object.
Also, I want to pass the integer-CheckID to the method.
Any help is highly appreciated.
Thanks in Advance!
***View***
<script type="text/javascript">
function showCheckImage(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var CheckID = dataItem.ID;
$.ajax({
url: '#Url.Action("GetDeferredCheckImage", "Customer")',
type: 'POST',
data: {deferredCheckID: CheckID },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(result) {
//var imageObj = result;
alert('Loaded Image Object!');
},
error: function (result) {
alert('Error occurred while loading the image object.');
}
});
}
**Controller Method**
[HttpPost]
public JsonResult GetDeferredCheckImage(int deferredCheckID)
{
try
{
QCEventLogger.Log($"Gathering deferred check image for check ID: {deferredCheckID}", LogType.Default);
var response = new AjaxGetDeferredCheckImageViewModel(deferredCheckID);
QCEventLogger.Log($"Result of service call to gather deferred check image. check ID: {deferredCheckID}. Success: {response.Success}", LogType.Default);
var DeferredCheckImageObject = response.ImageCheckObject.DeferredCheckImages.FirstOrDefault();
return Json(DeferredCheckImageObject, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var failureResponse = new AjaxGetDeferredCheckImageViewModel() { Success = false };
QCErrorLogger.Log($"Failure trying to gather deferred check image for check ID: {deferredCheckID}", ex);
return Json(failureResponse, JsonRequestBehavior.AllowGet);
}
}
Your ajax call might be like this,
$.ajax({
url: '#Url.Action("GetDeferredCheckImage", "Customer")',
type: 'POST',
data: { deferredCheckID: CheckID },
dataType: 'json',
success: function (result) {
//var imageObj = result;
alert('Loaded Image Object!');
},
error: function (result) {
alert('Error occurred while loading the image object.');
}
});
Related
I would like to call my WEB API in .NET Core from the jQuery like below:
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
JsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
return Json(welCome, JsonSettings);
}
catch(Exception ex)
{
throw ex;
}
}
And the jQuery caller:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "http://localhost:5000/api/mycontroller/GetText?callback=?",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
if (data.success) {
alert('Success -> ' + JSON.stringify(data.statusText));
}
},
error: function (data) {
alert('Error -> ' + JSON.stringify(data.statusText));
}
});
});
</script>
The API is calling successfully but it seems it will then redirect to error function in my Ajax and show the error alert with a "success" as it's statusText. I mean this: Error -> "Success" I am not sure why this happens?
I would like to print welCome as a success result and in the alert command.
Also please note that I am calling this API from another project, I mean the jQuery's AJAX code is inside another project. I am not sure if it is important or not at all.
The jQuery's AJAX Caller path: file:///C:/Users/Me/Desktop/Path/index.html
The API's address: C:\Users\Me\Documents\Visual Studio 2017\Projects\ThisProject\MyAPI
And the URL of this API: url: "http://localhost:5000/api/mycontroller/GetText",
Try the C# Code in the following manner :
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
return Ok(new { message = welCome });
}
catch(Exception ex)
{
throw ex;
}
}
Try the Jquery Code in the following manner :
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'GET',
url: 'http://localhost:5000/api/mycontroller/GetText',
success: function (response) {
alert('Success' + response.message);
},
failure: function (response) {
}
});
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")
}
}
});
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.
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")');
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.