jQuery post not working on safari but works on chrome - javascript

i've been facing a safari issue where a JQuery post method works on chrome but it does not on safari unless i set JQuery post async to false with this piece of code
$.ajaxSetup({ async: false });
also page redirect does not work on safari, but it works on chrome
window.location.href = data.url;
any idea why i'm getting this behavior on safari and how to fixe it.
here is the code that i'm using
$('#submit').click( function () { //post
if ($('form').validate().checkForm() === false) {
alert('Form is invalid.');
return;
}
var tool = $("#Tool").val();
var email = $("#Email").val();
var message = $("#Message").val();
var attachement0 = $("#Attachement0").val();
var attachement1 = $("#Attachement1").val();
var attachement2 = $("#Attachement2").val();
var attachement3 = $("#Attachement3").val();
var attachement4 = $("#Attachement4").val();
var dataToPost = {};
dataToPost.Tool = tool;
dataToPost.Email = email;
dataToPost.Message = message;
dataToPost.Attachement0 = attachement0;
dataToPost.Attachement1 = attachement1;
dataToPost.Attachement2 = attachement2;
dataToPost.Attachement3 = attachement3;
dataToPost.Attachement4 = attachement4;
// $.ajaxSetup({ async: false });
$.post("#Url.Action("BugReport_Send_JQuery","BugReport")", { model: dataToPost }).done(function (data) {
if (data.status == 1) {
alert(data.message);
window.location.href = data.url;
}
else if (data.status == 0) alert(data.error);
});
});
server side post method
[HttpPost]
public async Task<IActionResult> BugReport_Send_JQuery(User_BugReportViewModel model)
{
if (ModelState.IsValid)
{
var bugReport = new BugReportModel()
{
Tool = model.Tool,
Email = model.Email,
Message = model.Message,
Attachement0 = model.Attachement0,
Attachement1 = model.Attachement1,
Attachement2 = model.Attachement2,
Attachement3 = model.Attachement3,
Attachement4 = model.Attachement4,
Resolved = false,
CreationDate = DateTime.Now,
ResolutionDate = new DateTime(),
};
try
{
await appDBContext.BugReportsTB.AddAsync(bugReport);
await appDBContext.SaveChangesAsync();
}
catch (Exception e)
{
return Json(new { status = 0, error = e.Message });
}
return Json(
new
{
status = 1,
message = "A ticket has been created, Thank you for your coperations!",
url = Url.Action("TicketCreate", "Email", new { email = bugReport.Email }),
});
}
return Json(new { status = 0, error = "something went wrong!" });
}

Related

How i call a server function after close browser tab or browser in JavaScript

How i call a server function after close window tab or window in JavaScript.
Like this image
//This is my server code
public ActionResult DeleteNotPostedImage(string folder , string PostID)
{
folder = folder.Replace('_', '-');
string message = string.Empty;
try
{
if (Convert.ToInt32(PostID) <= 0)
{
if(Directory.Exists(Server.MapPath(string.Format("/ViewSolution/{0}", folder))))
{
Directory.Delete(Server.MapPath(string.Format("/ViewSolution/{0}", folder)), true);
}
}
return Json(new { success = true, message = message }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
MSError.Trace(ex);
}
return Json(new { success = false, message = message }, JsonRequestBehavior.AllowGet);
}
I want to call this function after close browser tab or browser .
<script type="text/javascript">
var contentStatus = false;
$(document).ready(function () {
var checkAction = "";
$('#your-post-btn').bind("click", function () {
checkAction = "Save";
$(this).data("clicked", true);
});
// on refresh
window.onbeforeunload = function(){
if($('#your-post-btn').data('clicked'))
{
checkAction = "Save";
return null;
} else {
checkAction = "Refresh";
return "Are you sure to leave this page";
}
};
// window close or tab close
window.onunload= function(){
if(checkAction.toLowerCase() !== "save"){
Test2();
}
};
function Test2(){
console.log(checkAction);
var formData = new FormData();
formData.append("folder",folder-name);
formData.append("PostID", post-id);
formData.append("action", checkAction);
var url = window.location.protocol.concat('//',window.location.host) + "/view/DeleteNotPostedImage";
window.navigator.sendBeacon(url, formData);
}
});

How to Open a URL/link in between a running ajax call and destroy all running ajax call?

I am working on Web page having an ajax call to the server and from the server(Controller) again a WCF service is called(which takes time) for fetching some data.
Inside server(Controller) i called to service in Parallel by using Task and async-await.
My problem is:
after opening the page that has code for calling the controller and WCF service, I can't redirect my tab/page to another URL by clicking on anchor tab present in UI. until ajax call result is retrieved.
UI CODE:
$(function () {
if (AutomationType.toLowerCase() === "desktop") {
$.ajax({
async: true,
url: "/" + AutomationType + "/Home/GetAllController",
data: { "hostName": hostname},
type: 'POST',
dataType: 'json'
}).success(function (response) {
debugger;
})
}
});
i have tried to abort the ajax call also as below,
$(function() {
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(i, jqXHR) { // cycle through list of recorded connection
jqXHR.abort(); // aborts connection
$.xhrPool.splice(i, 1); // removes from list by index
});
}
$.ajaxSetup({
beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); }, // annd connection to list
complete: function(jqXHR) {
var i = $.xhrPool.indexOf(jqXHR); // get index for current connection completed
if (i > -1) $.xhrPool.splice(i, 1); // removes from list by index
}
});
})
// Everything below this is only for the jsFiddle demo
$('a').click(function () {
$.xhrPool.abortAll();
});
Server(Controller) Code
public async Task<JsonResult> GetAllController(string hostName)
{
string IsControllerRunning = string.Empty;
var currentHost = string.Empty;
var currentRunId = string.Empty;
var currentStatus = string.Empty;
var ipDns = string.Empty;
Stopwatch sw = new Stopwatch(); sw.Start();
List<List<ExecutionStepResult>> returnresultArray = new List<List<ExecutionStepResult>>();
List<Task<IEnumerable<ExecutionStepResult>>> taskList = new List<Task<IEnumerable<ExecutionStepResult>>>();
Debug.WriteLine("starting 1 " + sw.Elapsed);
var resultArray = hostName.TrimEnd('^').Split('^');
for (int i = 0; i < resultArray.Length; i++)
{
string host = resultArray[i];
Task<IEnumerable<ExecutionStepResult>> task = new Task<IEnumerable<ExecutionStepResult>>(() => getServiceResultByTask(host));
task.Start();
taskList.Add(task);
}
foreach (Task<IEnumerable<ExecutionStepResult>> taskitem in taskList)
{
try
{
Debug.WriteLine("calling task " + sw.Elapsed);
IEnumerable<ExecutionStepResult> val = await taskitem;
returnresultArray.Add(val.ToList());
}
catch (Exception ex)
{
returnresultArray.Add(new List<ExecutionStepResult>() { new ExecutionStepResult() { IsError = true, ErrorMessage="true" ,CustomMessage = ex.Message.ToString() } });
}
}
for (int i = 0; i < resultArray.Length; i++)
{
string host = resultArray[i];
currentHost = host.Split('|').GetValue(1).ToString();
currentStatus = host.Split('|').GetValue(2).ToString();
currentRunId = host.Split('|').GetValue(0).ToString();
ipDns = host.Split('|').GetValue(3).ToString();
List<ExecutionStepResult> exeResponse = returnresultArray[i].ToList();
if (exeResponse.Count() > 0 && (currentStatus != "3" || (currentStatus == "3" && exeResponse[i].ErrorMessage == "true")))
IsControllerRunning += host + "|" + exeResponse[0].CustomMessage + "^";
else if (exeResponse.Count() > 0 && currentStatus == "3" && exeResponse[0].ErrorMessage == "false")
IsControllerRunning += host;
}
Debug.WriteLine("end " + sw.Elapsed);
sw.Stop();
return Json(IsControllerRunning, JsonRequestBehavior.AllowGet);
}
calling WCF service:
private IEnumerable getServiceResultByTask(string hosts)
{
using (var service = new RemoteCommandClient())
{
try
{
System.Threading.Thread.Sleep(15000);
string currentHost = hosts.Split('|').GetValue(1).ToString();
string currentStatus = hosts.Split('|').GetValue(2).ToString();
string currentRunId = hosts.Split('|').GetValue(0).ToString();
string ipDns = hosts.Split('|').GetValue(3).ToString();
IEnumerable<ExecutionStepResult> result = service.ExecuteRemoteWithRunId("CHECK_CURRENT_EXECUTION", Convert.ToInt32(currentRunId));
return result;
} catch (Exception ex)
{ throw ex; }
}
}
Still, I don't know how to open /redirect a page URL if an ajax call is running on the server. I am using signalR in the same page also. Please help.

how do I get my Ajax to return a function and prevent my document from downloading onclick

I have been trying to figure this out for hours.
I have the following document path on and anchor tag
#link.Title
I do not want to process the href if the "checkAuth" function returns a false.
Here is the "checkAuth" code.
var checkAuth = function(id, PasswordProtected) {
var result = null;
var hostname = location.hostname;
var host = '#System.Configuration.ConfigurationManager.AppSettings["hostroot"]';
if (hostname == "localhost")
host = "";
if (PasswordProtected == "1"){
var pass = prompt("This document is password protected", "");
var response = $.ajax({
type: "GET",
url: host + "/Communities/DeCryptPwd/",
data: {"id": id, "password": pass},
success: function (data) {
alert(data);
if (data == "True")
result = true;
if (data == "False")
result = false;
},
error: function (errorData) { alert(errorData); }
});
}
I just don't know how to stop the processing of the document on the href and return a true ... continue process, or false -- stop processing.
Just in case you need it, here is the "sever side" code called by the .ajax
public bool DeCryptPwd(int id, string password) {
var encrypted = db.CommunityDocs.Where(x => x.Id == id).Select(x => x.Password).SingleOrDefault();
/* Extract the bytes */
byte[] hashBytes = Convert.FromBase64String(encrypted);
/* Get the salt */
byte[] salt = new byte[16];
Array.Copy(hashBytes, 0, salt, 0, 16);
/* Compute the hash on the password the user entered */
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
/* Compare the results */
for (int i = 0; i < 20; i++)
if (hashBytes[i + 16] != hash[i])
return false;
return true;
}
You cannot return the result from an async function from the function that contains it. So you need to change the location in the success part and return true if not protected.
However the code will currently allow them to right-click and open in new window regardless
function checkAuth = function(theLink) {
var id = theLink.id,
protected = theLink.getAttribute("pass") == "1",
href = theLink.href,
result = null,
hostname = location.hostname,
host = '#System.Configuration.ConfigurationManager.AppSettings["hostroot"]';
if (hostname == "localhost")
host = "";
if (protected) {
var pass = prompt("This document is password protected", "");
var response = $.ajax({
type: "GET",
url: host + "/Communities/DeCryptPwd/",
data: {
"id": id,
"password": pass
},
success: function(data) {
alert(data);
if (data == "True") {
location = href;
}
},
error: function(errorData) {
alert(errorData);
}
});
return !protected; // return false if protected
}
#link.Title

Parse "Unexpected identifier in main.js" in my Cloud Code

I am trying to deploy my newly written cloud code function to Parse but I keep getting the error "Unexpected identifier" at line 110, I can't seem to figure out how there is an error here, any help?
Parse.Cloud.define("backgroundJob", function(request, response) {
Parse.Cloud.useMasterKey();
var moments = require("cloud/moments.js");
var now = moments.moment();
var groupObject = Parse.Object.extend("Group");
var query = new Parse.Query(groupObject);
var eventObject = Parse.Object.extend("Event");
query.find().then(function(groups) {
var promise = Parse.Promise.as();
_.each(group, function(result) {
promise = promise.then(function() {
var count = 0;
var events = _.map(result.get("Events"), function(eventArray) {
if (now == eventArray[count].get('date') {
var curEvent = eventArray[count];
eventArray[count].destory();
var relationc = result.get("created");
var createdq = relationc.query();
var relationj = result.get("created");
var joinedq = relationj.query();
var partOnee = curEvent.get("name");
var outString = partOnee.concat(" is now");
Parse.Push.send({
where: createdq,
data: {
alert: outString
}
}).then(function() {
response.success();
}, function(error) {
response.error(error);
});
Parse.Push.send({
where: joinedq,
data: {
alert: outString
}
}).then(function() {
response.success();
}, function(error) {
response.error(error);
});
}
count = count+1;
});
});
});
}).then(function() {
response.success()
}, function(error) {
response.error(error);
});
});
Line 110 is var curEvent = eventArray[count];
You missed ) in this line if (now == eventArray[count].get('date'), see:
var events = _.map(result.get("Events"), function(eventArray) {
if (now == eventArray[count].get('date') {
Fix:
var events = _.map(result.get("Events"), function(eventArray) {
if (now == eventArray[count].get('date')) {
Note, when interpreters/compilers (in most programming languages) say there is a problem on a line, usually the problem can be in any row before.

Javascript processing and ASP.NET MVC

I have the following javascript and JsonResult. The issue I am having is the ajax post doesn't allow enough time for JsonResult to return the appropriate data. I probably don't completely understand javascript processing and I'm sure this is by design but I'm wondering how I can make this a synchronous request. In short, wait for the JsonResult action to complete before the javascript continues processing.
<script type="text/javascript">
$(document).ready(function () {
var table = document.getElementById("updateTable");
var tasks = new Array("shutdown", "prep", "boot", "ready");
var tasksLength = tasks.length;
for (var i in tasks) {
for (var loop = 1, max = table.rows.length; loop < max; loop++) {
id = table.rows[loop].cells[0].innerHTML;
task = tasks[i];
ImageUpdateStatus = {
ImageId: parseInt(id),
Task: task,
Status: "pending"
}
$.ajax({
type: "POST",
url: "UpdateStatus",
data: $.postify(ImageUpdateStatus),
success: function (data) {
var status = data.status;
}
});
ImageUpdateStatus.Status = status;
if (ImageUpdateStatus.Status == "success") {
task = task.concat(" ");
document.getElementById(task.concat(id)).src = "/PVSUtil_ver2/Assets/Images/Image.Success.png";
j = parseInt(i) + 1;
if (j < tasksLength) {
nextTask = tasks[j];
nextTask = nextTask.concat(" ");
document.getElementById(nextTask.concat(id)).src = "/PVSUtil_ver2/Assets/Images/Image.Load.gif";
}
}
}
}
document.getElementById('nextButton').className = "navigation";
document.getElementById('nextButton').disabled = false;
});
//
// GET: /Build/UpdateStatus
public JsonResult UpdateStatus(ImageUpdateStatus imageUpdateStatus, SessionStateItemCollection sessionItems = null)
{
var data = new object();
string status = null;
ImageInfo imageInfo = new ImageInfo();
IImageInfoServices svcImageInfo = new ImageInfoServicesRepository();
imageInfo = svcImageInfo.GetImageByImageId(imageUpdateStatus.ImageId);
IDeviceControlServices svcDevice = new DeviceControlServicesRespository();
IPVSCommandServices svcPVSCmds = new PVSCommandServicesRespository();
if (imageUpdateStatus.Task == "shutdown")
{
status = svcDevice.Shutdown(imageInfo.ImageId);
//status = "success";
data = new
{
status
};
}
if (imageUpdateStatus.Task == "prep")
{
List<UpdateReasonForm> updateReasonForms;
if (sessionItems.Keys.Count > 0)
{
updateReasonForms = sessionItems["UpdateReasonForms"] as List<UpdateReasonForm>;
}
else
{
updateReasonForms = Session["UpdateReasonForms"] as List<UpdateReasonForm>;
}
foreach (var item in updateReasonForms)
{
if (item.ImageId == imageInfo.ImageId)
{
status = svcPVSCmds.PrepImage(imageInfo, item.NewVersion);
}
}
data = new
{
status
};
}
if (imageUpdateStatus.Task == "boot")
{
status = svcDevice.Boot(imageInfo.ImageId);
data = new
{
status
};
}
if (imageUpdateStatus.Task == "ready")
{
status = "success";
data = new
{
status
};
}
return this.Json(data, JsonRequestBehavior.AllowGet);
}
Just move the code that relies on the result from the ajax request into the success callback function:
$.ajax({
type: "POST",
url: "UpdateStatus",
data: $.postify(ImageUpdateStatus),
success: function (data) {
ImageUpdateStatus.Status = data.status;
if (ImageUpdateStatus.Status == "success") {
task = task.concat(" ");
document.getElementById(task.concat(id)).src = "/PVSUtil_ver2/Assets/Images/Image.Success.png";
j = parseInt(i) + 1;
if (j < tasksLength) {
nextTask = tasks[j];
nextTask = nextTask.concat(" ");
document.getElementById(nextTask.concat(id)).src = "/PVSUtil_ver2/Assets/Images/Image.Load.gif";
}
}
}
});
You don't want to make the request synchronous; you want to put all code that depends on the result into your callback:
$.ajax({
type: "POST",
url: "UpdateStatus",
data: $.postify(ImageUpdateStatus),
success: function (data) {
var status = data.status;
ImageUpdateStatus.Status = status;
if (ImageUpdateStatus.Status == "success") {
task = task.concat(" ");
document.getElementById(task.concat(id)).src = "/PVSUtil_ver2/Assets/Images/Image.Success.png";
j = parseInt(i) + 1;
if (j < tasksLength) {
nextTask = tasks[j];
nextTask = nextTask.concat(" ");
document.getElementById(nextTask.concat(id)).src = "/PVSUtil_ver2/Assets/Images/Image.Load.gif";
}
}
}
});
$.ajax({
type: "POST",
async: false,
url: "UpdateStatus",
data: $.postify(ImageUpdateStatus),
success: function (data) {
var status = data.status;
}
});
but you really should avoid this, you should really look into making your application work with that wait for the ajax request
I really feel that you should aggregate any data you need to render your view for the first time on the server side and then push it down to the page. You could use JavaScript to do the rendering once the data is in the page (could be stored in JSON format in a hidden field) but I don't think it's optimal to have the page making an Ajax call when it's rendering for the first time.

Categories