I am using MVC and I want to show message as toast base on my function result from controller.
My code is working from one step behind.
Here is My View:
#(Html.DevExtreme()
.Button()
.Icon("check")
.Hint("Check the User")
.OnClick("function(e) {CheckUser(e,data,rowIndex) }")
)
function CheckUser(e, f, g) {
console.log(e)
console.log(f.InsertedUserId)
console.log(f.AdminUserId)
$.ajax({
type: "POST",
url: '#Url.Action("CheckUser","UserRoleManagement")',
data: " {AdminUserId: '" + f.AdminUserId + "', InsertedUserId:'" + f.InsertedUserId + "', IsCSOUser: 'False'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (result) {
var a = '#TempData["CheckerResult"]';
if (a.toString() == "Succes") {
showToast(e)
}
else {
showToast3(e)
}
console.log(result);
}
})
};
function showToast(e) {
console.log('showToast');
$("#toast").dxToast({
message: 'Updated succesfully',
type: 'success',
displayTime: 3000,
maxWidth: 500,
height: "auto",
animation: { show: { type: 'fade', duration: 400, from: 0, to: 1 }, hide: { type: 'fade', duration: 400, to: 0 } },
position: { my: 'center bottom', at: 'center bottom', of: window }
});
$("#toast").dxToast("show");
}
function showToast3(e) {
console.log('showToast');
$("#toast").dxToast({
message: 'Process Failed.',
type: 'error',
displayTime: 3000,
maxWidth: 500,
height: "auto",
animation: { show: { type: 'fade', duration: 400, from: 0, to: 1 }, hide: { type: 'fade', duration: 400, to: 0 } },
position: { my: 'center bottom', at: 'center bottom', of: window }
});
$("#toast").dxToast("show");
}
Here is my Controller:
[HttpPost]
public ActionResult CheckUser(string AdminUserId, string InsertedUserId, bool IsCSOUser)
{
RoleGroupRepository rep = new RoleGroupRepository();
//TempData["Success"] = "User is checked Successfully.";
SiteSession session = (SiteSession)SessionManager.ReturnSessionObject(SessionKeys.MainSession);
long CurrentLoggedUserId = session.AdminUserId;
if (CurrentLoggedUserId == Convert.ToInt64(InsertedUserId))
{
TempData["CheckerResult"] = "User check is not Successful.";
pLogger.INF("User check is not Successful. User can not check by the Inserted User.");
return Json(new { success = false, responseText = "Fail! User is not checked!" }, JsonRequestBehavior.AllowGet);
}
ReturnValuesParser returnValues = rep.CheckUser(AdminUserId, Convert.ToString(CurrentLoggedUserId), IsCSOUser);
if (returnValues.ReturnCode == 1)
{
TempData["CheckerResult"] = "Succes";
return Json(new { success = true, responseText = "Succes" }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["CheckerResult"] = "User check is not Successful.";
pLogger.INF("User check is not Successful" + returnValues.returnDescription_En);
}
return Json(new { success = false, responseText = "Fail! User is not checked!" }, JsonRequestBehavior.AllowGet);
}
What should i change here to show my message base on the TempData["CheckerResult"] result? It is always getting reference one step behind. I logically get the issue but don't know how to resolve.
will be grateful for any response. Cheers
You're examining the value that was present when you first rendered the view:
var a = '#TempData["CheckerResult"]';
But not using anything from the returned result in the AJAX call:
result
Take a look at the page source in your browser and observe how #TempData["CheckerResult"] essentially becomes a hard-coded literal value to your JavaScript code. It's not going to change.
Basically, don't use TempData when you're not returning a view. You're returning JSON, which contains the information you want:
return Json(new { success = true, responseText = "Succes" }, JsonRequestBehavior.AllowGet);
So examine that returned information in your AJAX response handler:
if (result.responseText == "Succes")
You'll also want to change this:
dataType: "html"
to this:
dataType: "json"
Because you're expecting JSON back from the server, not HTML.
Related
I have an aps.net MVC5 web app, I have a controller action post method that looks like this,
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Set(int id)
{
DbHelper dbHelper = new DbHelper();
dbHelper.Update<News>("update news set ispublished = 1, publishdate = #PublishDate where newsid = #NewsId", new { NewsId = id, PublishDate = DateTime.Now });
return Json(new { success = true, message = "added successfully!", redirectToUrl = Url.Action("NewsList", "Home") }, JsonRequestBehavior.AllowGet);
}
Now, when I call this method from my View ,
$(document).on("click", ".set", function () {
var mId = $(this).attr("data-model-id");
$.ajax({
url: "#Url.Action("Set","Home")",
data: { "id": mId },
contentType: 'application/json',
type: 'POST',
dataType:'json',
success: function (response) {
if (response.success) {
window.location.href = response.redirectToUrl;
dt.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
});
}
},
error: function (response) {
$.notify(response.message, {
globalPosition: "top center",
className: "success"
});
}
});
});
I am always getting this enter image description here
I expect to be redirected to home/newslist url. I tried changing all the parameters of ajax call , adding and removing them, still no matter what I do, I always land at this page.
Try to check after remove the "error" function from your ajax. Also you can try this:
$(document).on("click", ".set", function () {
var mId = $(this).attr("data-model-id");
$.ajax({
url: "#Url.Action("Set","Home")",
data: { "id": mId },
contentType: 'application/json',
type: 'POST',
dataType:'json',
success: function (response) {
if (response.success) {
window.location.href = response.redirectToUrl;
dt.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
});
}
},
error: function (jqXHR, textStatus, errorThrown) {
$.notify(errorThrown, {
globalPosition: "top center",
className: "success"
});
}
});
});
Check if success function is calling or not.
If you need return the full HTML page in ajax response then you need to change Controller method with some changes.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Set(int id)
{
DbHelper dbHelper = new DbHelper();
dbHelper.Update<News>("update news set ispublished = 1, publishdate = #PublishDate where newsid = #NewsId", new { NewsId = id, PublishDate = DateTime.Now });
//return Json(new { success = true, message = "added successfully!", redirectToUrl = Url.Action("NewsList", "Home") }, JsonRequestBehavior.AllowGet);
return view("ViewName");
}
on some button's click event I'm calling function a() which contains below mentioned Ajax call, in the success I'm using $.Deferred. It works perfectly fine on very first click of the button but when I click a button second, third, fourth... or nth time it does not work as expected (It does not go inside of confirmation function at all). what I'm doing wrong. Thank you in advance.
$.ajax({
type: "GET",
url: "some url",
data: {
parameters
},
success: function (result) {
//result is an Array object. for example **result:Array[3]**, further expand result will be like this **result[0]:Array[19], result[1]:Array[39], result[2]:Array[15]**
var defer = $.Deferred();
function confirmation(result) {
if (result.length > 1) {
$('#field' + questionID).append('<div id=dialog></div>');
$("#dialog").append('<div id=grid></div>');
$("#dialog").kendoDialog({
modal: true,
visible: false,
draggable: true,
closable: false,
title: "Please Select One Submission",
maxWidth: 500,
//maxHeight:300,
animation: {
open: {
effects: "slideIn:down fadeIn",
duration: 500
},
close: {
effects: "slide:up fadeOut",
duration: 500
}
},
actions: [
{ text: 'OK', primary: true, action: onOK }
]
});
$("#grid").kendoGrid({
dataSource: {
data: result,
schema: {
data: function (result) {
return $.map(result, function (item) {
return $.map(item, function (innerData) {
for (var i = 0; i < displayFields.length; i++) {
if (displayFields[i] == innerData.FieldIDString) {
return {
EntryGroupID: innerData.EntryGroupID,
FieldTextString: innerData.FieldTextString,
EntryValue: innerData.EntryValue
}
}
}
});
});
}
},
pageSize: 2,
group: { field: "EntryGroupID" }
},
filterable: {
mode: "row"
},
pageable: {
refresh: true,
},
noRecords: {
template: "No records to display"
},
groupable:false,
//scrollable: true,
selectable: true,
columns: [{
field: "EntryGroupID",
title: "Submissions",
filterable: {
cell: {
operator: "contains"
}
}
}, {
field: "FieldTextString",
title: "Questions",
filterable: {
cell: {
operator: "contains"
}
}
}, {
field: "EntryValue",
title: "Answers",
filterable: {
cell: {
operator: "contains"
}
}
}]
});
var wnd = $("#dialog").data("kendoDialog");
wnd.wrapper.find('.k-dialog-title').css('background', CIMSFields.backgroundColour).css('color', CIMSFields.textColour).css('width','100%').css('text-align','center');
wnd.open().center(true);
//in this function i'm waiting for user response which they will choose one array object based on this value **Confirmation** function will get the data.
function onOK(e) {
var data = [];
var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());
if (selectedItem != null) {
$.map(result, function (item) {
if (selectedItem.EntryGroupID == item[0].EntryGroupID) {
data.push(item);
defer.resolve(data);
}
});
}
else {
defer.resolve(data);
}
wnd.close();
}
}
else
{
defer.resolve(result);
}
return defer.promise();
}
alert(defer.state());
confirmation(result).then(function (data) {
//it never reach here except first time
alert(defer.state());
alert(data);// data is the user selected value from the grid.
})
}
});
If result is an array, .empty is not an Array property or method. $.Deferred() is not necessary, $.ajax() returns a jQuery promise object.
You can check .length of expected array, or property of expected object at .then() chained to a() call. Also, chain .fail() to log and handle errors that could possibly occur.
function a(/* parameters */) {
// note, we are `return` ing `jQuery.ajax()` call,
// which returns a jQuery promise object
return $.ajax({type: "GET", url: "some url", data: {parameters}})
}
a()
.then(function(result, textStatus, jqxhr) {
console.log(result.length, jqxhr.state());
if (result.hasOwnProperty("empty")) { console.log(result.empty); }
else { console.log("result does not have property \"empty\""); };
})
// log, handle errors here
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown, jqxhr.state());
});
found my answer here
basically my need was I have to wait for user response in the function before proceeding further. Thank you all who took time to respond my question. I appreciate your time and effort. Most importantly I'm not using deferred at all now.
I am trying to show results not found message when there's no suggestion from user input. typeahead.js shows input suggestion while giving input to text field..if there no suggestion found then how to show results not found message?.. version is typeahead.js 0.11.1
You can check if no result with empty parameter:
I have edited above code a little bit so that it may help to others searching the same thing.
$('.typeahead').typeahead({
hint: false,
highlight: true,
minLength: 3,
},
{
name: 'firstnames',
displayKey: 'value',
source: firstnames.ttAdapter(), // this is your result variable
templates: {
empty: function(context){
// console.log(1) // put here your code when result not found
$(".tt-dataset").text('No Results Found');
}
}
I have the same issue. But i'm using ajax for my source not adapter. You can try adding popover if suggestions length is 0.
function BindControls_facility(facility_names,facility_details,id) {
var timeout;
$('#facility_names'+id).typeahead({
items: "all",
// source: facility_names,
source : function (query, result) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$.ajax({
url: master_url + "/facility_name_dropdown_list",
method: 'POST',
xhrFields: {
withCredentials: false
},
data: { input_query : query},
success: function (data) {
if(Object.keys(data.facility_name).length > 0){
// $("#facility_names"+id).popover('destroy');
result($.map(data.facility_name, function (item) {
return item;
}));
}
else{
$('#facility_names'+id).popover({container: '#botdiv'+id,placement: 'top'}).popover('show');
$('#facility_names'+id).attr('data-content','No result found for \"'+$("#facility_names"+id).val()+'\"').data('bs.popover').setContent();
setTimeout(function () {
$('#facility_names'+id).popover('destroy');
}, 2000);
}
}
});
}, 300);
},
hint: true,
highlight: true,
cache: true,
compression: true,
minLength: 3,
updater: function(item) {
var details = "";
$.ajax({
url: master_url + "/get_facility_name",
method: 'POST',
xhrFields: {
withCredentials: false
},
data: { facility_name : item},
success: function (data) {
console.log(data.status);
}
});
return item;
}
});
}
I tried showing this "no results found" warning using bootstrap-popover. I know its not a good one to try but i just shared my way to achieve this if i had the same issue.
I'm looping through data from a .net web service through jsonp. Similar code works elsewhere but I can't see where i've gone wrong here.
The data is retreived through:
if (pageId === 'alerts') {
var Username = localStorage.getItem("Username");
var SessionKey = localStorage.getItem("SessionID");
console.log(Username);
console.log(SessionKey);
$.mobile.loading( 'show', { theme: "b", text: "Loading", textonly: false});
$.ajax({
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: "http://redacted/GetData.asmx/GetLostAnimals",
data: {Username: Username, SessionKey: SessionKey },
dataType: "jsonp",
success: myAlerts
});
}
var lostSelectedPet = 0;
function myAlerts(data)
{
$("#alertsListMissingPets").empty();
$.mobile.loading( 'hide', { theme: "b", text: "Loading", textonly: false});
$.each(data, function(index) {
console.log(data[index].LostDate)
$("#alertsListMissingPets").append(" <li>"+ data[index].AnimalKey + " <span class=\"ui-li-count\">12</span></li>");
});
$("#alertsListMissingPets").listview('refresh');
}
$(document).on('click', '#alertsListMissingPets li a', function(){
localStorage.setItem("lostSelectedPet", $(this).attr('data-custom'));
editingId = $(this).attr('data-custom');
});
The json returned is like:
callback(
{
AnimalKey: "f152e1c6baca181d9f3ca1f18c91cc41f23fc122545d9c8bff9f4cb2ea449874",
LostDate: "11/06/2014 16:14:19",
FoundDate: "",
LostKey: "7560733274a7ca2ec43a85fcb9abd345fdc876acffac2b75ace7946035122fbd",
Resp: "OK"
}
)
However, this returns - It shows 5 items but theres only one result, the json above is the full response.
You are not looping over an array, you are looping over an object. You have 5 keys in the object, hence why there is 5 rows in the output.
Change the response to be an array.
callback(
[{ //<-- added [
AnimalKey: "f152e1c6baca181d9f3ca1f18c91cc41f23fc122545d9c8bff9f4cb2ea449874",
LostDate: "11/06/2014 16:14:19",
FoundDate: "",
LostKey: "7560733274a7ca2ec43a85fcb9abd345fdc876acffac2b75ace7946035122fbd",
Resp: "OK"
}] //<-- added ]
)
I have the following jQuery function. I do not want to display the JSON data that is returned. I just want my dialog box to show a message to the user. What is strange is that sometimes I get a dialog message as desired and sometimes I get a page with the raw JSON response. What might cause such an intermittent problem?
$("#btnSubmit").click(function (event) {
event.preventDefault();
$.ajax({
url: "/Transfer/Receive?TransferID=" + $("#TransferID").val(),
dataType: "json",
type: "post",
success: function (data) {
if (data.Message == "success") {
$("#divTransferNo").dialog("destroy");
$("#systemMsg").dialog({ autoOpen: true, title: "System Message", height: 150, modal: true });
$("#systemMsg").html("<p>Transfer Received Successfully.</p>");
$('div#systemMsg').bind('dialogclose', function (event) {
window.location = "../DrawMandrel/";
});
}
else if(data.Message=="verifyreceiveback") {}
else if (data.ErrorType == "validation") {
$("#systemMsg").dialog({ autoOpen: true, title: "System Message", height: 150, modal: true });
$("#systemMsg").html("<p>ERROR - This transfer has already been received.</p>");
}
else {
$("#systemMsg").dialog({ autoOpen: true, title: "System Message", height: 150, modal: true });
$("#systemMsg").html("<p>ERROR - Check your transfer number.</p>");
}
}
});
});
UPDATE:
I just received the response below which should have called:
else {
$("#systemMsg").dialog({ autoOpen: true, title: "System Message", height: 150, modal: true });
$("#systemMsg").html("<p>ERROR - Check your transfer number.</p>");
{"Message":"ERROR: This transfer has already been completed.","ErrorType":"validation","ErrorMessage":"ERROR: This transfer has already been completed.","OperationMessage":"ERROR: This transfer has already been completed.","BarCode":null}
UPDATE:
So I changed my ajax request to:
$.ajax({
url: "/Transfer/Receive?TransferID=" + $("#TransferID").val(),
dataType: 'json',
type: 'post',
accept: {
json: 'application/json',
xml: 'application/xml'
},
success: function (data) {
And I am producing the following Request Headers: