Browser is intermittently showing JSON when I do not want it to - javascript

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:

Related

Show toast message by calling from controller

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.

Loading html inside sweet alert?

Here is my code for callling Swal:
window.swal({
title: "Checking...",
text: "Please wait",
imageUrl: "{{ asset('media/photos/loaderspin.gif') }}",
showConfirmButton: false,
allowOutsideClick: false
});
$.ajax({
type: 'POST',
url: '/' + target,
data: {
data: true
},
success: function(response) {
window.swal({
type: 'info',
width: 900,
padding: '3em',
html: response,
showCloseButton: true,
focusConfirm: false,
});
},
error: function(response) {
}
});
Basically I'm making an ajax request that does a return view('index', compact('data')); in the controller.
The html that I'm trying to load inside Swal has a <script src="my-file.js"></script> inside it, but it does not get loaded when Swal is fired, so no events get fired when I click inside.
I've tried looking in the docs but I can't find anything. How will I get swal to load that file?
I was able to solve this by adding this line inside the success block:
$.getScript('my-file.js')

How to load a partial view in an iframe on ajax call?

I am working on MVC 4 and trying to load a partial view in an iframe using $.ajax call like this :
$(document).ready(function () {
$("#btnInsert").click(
function(e) {
e.preventDefault();
var loc = window.location.href;
loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "Home" : loc;
console.log(loc + "/Insert");
$.ajax({
type: "GET",
url: loc+ "/Insert",
success: function (msg) {
console.log(msg);
//$('FrameforPopUp.html').html(msg);
//$("#ShowNextView").css(
$("#ShowNextView").html(msg);
//$("ShowNextView").src
showView(msg);
$("#ShowNextView").attr("disabled", "enabled");
//if (msg.d)
// showView(msg.d);
//else
// alert("Data is invalid")
},
error: function () {
alert("An unexpected error has occurred during processing.");
}
});
});
function showView(resultView) {
$("#ShowNextView").dialog({ //resultView
modal: true,
width: "auto",
height: "auto",
position: "center",
resizable: false,
closeOnEscape: true,
open: function (ev, ui) {
}
});
}
and my frame is as follows :
<iframe id="ShowNextView" style="visibility:hidden;">
but it is not showing iframe with a pop up..
I want that iframe to load the "Insert" view and show it in pop up after the ajax call on the btnInsert click. Please help?
This is how you can write HTML content into iframe.
$("#btnInsert").click(function (e) {
// ...
$.ajax({
type: "GET",
url: loc + "/Insert",
success: function (msg) {
showView(msg);
},
error: function () {
alert("An unexpected error has occurred during processing.");
}
});
});
function showView(resultView) {
$('<div>').append('<iframe id="ShowNextView"></iframe>').dialog({
modal: true,
width: "auto",
height: "auto",
position: "center",
resizable: false,
closeOnEscape: true,
open: function (ev, ui) {
$(this).find('#ShowNextView').contents().find('body').html(resultView);
}
});
}
And also remove <iframe id="ShowNextView" style="visibility:hidden;"> from HTML.
Demo: http://jsfiddle.net/ssqxyvjc/

syntax error jquery handle json

Firebug says that there's a syntax error near:
if (json['name'] !="")
But I still can't find it. This is part of a long poll script that hangs until the server sends a response. When the server response is empty, it throws the error near if (json['name'] !="")
var timestamp=null;
function waitForMsg(){
$.ajax({
type: "GET",
url: "auth/classes/getdata.php?id="+6,
async: true,
cache: false,
success: function(data){
var json=eval('('+data+ ')');
if (json['name'] !=""){
if(json['type'] ==1){
$.notification({
content: json['name']+" liked a post",
showTime: true,
icon: '8',
timeout: 10000,
click: function() {
window.location.href = "http://www.test.com/posts.php?post="+json['post'];
}
});
}
if(json['type'] ==2){
$.notification({
content: json['name']+" disliked a post",
showTime: true,
icon: 'Y',
timeout: 10000,
click: function() {
window.location.href = "http://www.test.com/posts.php?post="+json['post'];
}
});
}
if(json['type'] ==3){
$.notification({
content: json['name']+" commented a post",
showTime: true,
icon: 'i',
timeout: 10000,
click: function() {
window.location.href = "http://www.teest.com/posts.php?post="+json['post'];
}
});
}
}
setTimeout("waitForMsg()",1000);
},
error: function(XMLHttpRequest,textStatus,errorThrown) {
// alert("error: "+textStatus + " "+ errorThrown );
setTimeout("waitForMsg()",15000);
}
});
}
$(document).ready(function() {
waitForMsg();
});
When the server response is empty, it throws the error near if (json['name'] !="")
So check to see if there is data
if(!data || !data.length) {
return;
}
var json=eval('('+data+ ')');
Modern day browsers support JSON.parse() and also jQuery will automtically do this for you if you return the correct content type from the server.
Why don't you use "dataType: 'json'" as an attribute of you ajax call? That would create a json object from the response and you can work directly with that variable.
$.ajax({
type: "GET",
url: "auth/classes/getdata.php?id="+6,
async: true,
cache: false,
dataType: "json",
success: function(data){
var json=data; //or you can work directly with data
If you return an empty message from your server ("" instead of "{}"), it will trigger the "error" function of your ajax call, since it will throw a parse exception.
Hope this helps you.
Regards,
Marcelo

error from dialog when using jquery and ajax

I get a an alert: Object XMLHttpRequest. This happens when I click Add Recipient on my dialog. The code below POSts the new values to the database. It opens a dialog or form and the action of the form is to add or insert a new value to the database. I pasted the code below because I think thats likely the source of the error.
Below is the javascript for my code:
$(function () {
$('#dialog-form-add').dialog({
autoOpen: false,
modal: true,
height: 425,
width: 475,
buttons: {
'Add Recipient': function () {
$.ajax({
type: "POST",
url: $("#add-recipient-form").attr('action'),
data: $("#add-recipient-form").serialize(),
dataType: "text/plain",
success: function (response) {
$('#dialog-form-add').dialog('close');
$("#grid").load('/Default/ #grid', function () {
$('tbody > tr:first')
.effect("highlight", {}, 2000);
});
},
error: function (response) {
alert(response);
$('#dialog-form').dialog('close');
}
});
},
Cancel: function () {
$('#dialog-form-add').dialog('close');
}
}
});
$('#requestdate').datepicker({ dateFormat: 'yy-mm-dd' });
$('#add-recipient')
.button().click(function () {
$('#dialog-form-add').dialog('open');
});
});

Categories