I am trying to find a way to keep my session alive when Controller is taking long time to come back with results. My Javascript on button click looks like below:
function OnClick(s, e) {
positionDate = ReportingPositionDate.GetDate().toDateString();
if (true) {
$.ajax({
type: "POST",
url: "#Url.Action("DataFileUpload", "ImportData")",
data: JSON.stringify({ positionDate: positionDate }),
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function () { lpImport.Show(); },
success: function (msg) {
debugger;
ImportDataGridView.PerformCallback();
ImportSuccessMessage.SetVisible(true);
ImportSuccessMessage.SetText(msg);
lpImport.Hide();
},
Error: function (xhr) {
alert(xhr)
ImportDataGridView.PerformCallback();
}
});
}
}
basically session times out before I get Success. I would like to silently keep session alive.
Thanks all.
I searched the web for same. There were responses but they were incorrect.
I was eventually able to tweak one of them, and this is the result:
-- Create an asp.net mvc app;
add the following to the home controller:
[HttpPost]
public JsonResult KeepSessionAlive()
{
return new JsonResult { Data = "Postback " + on " + DateTime.Now};
}
----Add the following to index.cshtml:
<div id="myDiv"></div>
#section scripts{
<script src="~/SessionUpdater.js"></script>
<script type="text/javascript">
SessionUpdater.Setup('#Url.Action("KeepSessionAlive","Home")');
</script>
}
-- reference the following js file [in addition to referencing jquery]
SessionUpdater = (function () {
var clientMovedSinceLastTimeout = false;
var keepSessionAliveUrl = null;
//var timeout = 5 * 1000 * 60; // 5 minutes
var timeout = 15000; // 15 seconds for testing
function setupSessionUpdater(actionUrl) {
// store local value
keepSessionAliveUrl = actionUrl;
// alert(actionUrl);
// setup handlers
listenForChanges();
// start timeout - it'll run after n minutes
checkToKeepSessionAlive();
}
function listenForChanges() {
$("body").on("mousemove keydown", function () {
clientMovedSinceLastTimeout = true;
});
}
// fires every n minutes - if there's been movement ping server and restart timer
function checkToKeepSessionAlive() {
setTimeout(function () { keepSessionAlive(); }, timeout);
}
function keepSessionAlive() {
// if we've had any movement since last run, ping the server
if (!clientMovedSinceLastTimeout && keepSessionAliveUrl != null) {
$.ajax({
type: "POST",
url: keepSessionAliveUrl,
success: function (data) {
$('#span').text(data);
$('#myDiv').append('<br/>' + data);
// reset movement flag
clientMovedSinceLastTimeout = false;
// start listening for changes again
listenForChanges();
// restart timeout to check again in n minutes
checkToKeepSessionAlive();
},
error: function (data) {
alert("ERROR");
console.log("Error posting to " & keepSessionAliveUrl);
}
});
}
else {
clientMovedSinceLastTimeout = false;
listenForChanges();
checkToKeepSessionAlive();
}
}
// export setup method
return {
Setup: setupSessionUpdater
};
})();
Related
I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
var elemEmployee = 55;
var startDT = $('#searchFilterStartDate').val();
var endDT = $('#searchFilterEndDate').val();
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data);
}
});
}
here's my controller:
[HttpGet]
public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
return entity.GetDTR(data);
}
As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.
You need to return JSON from your Controller method. You can change your method to:
[HttpGet]
public JsonResult GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
var getDTR= entity.GetDTR(data);
return Json(new {dtrData= getDTR});
}
And in your Ajax call:
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data.dtrData);
},
error: function(error) {
console.log(error)
}
});
After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
//On Clink "Search Button"
$("#searchbtn").click(
function () { GetRecord(); });
});
The data seems to be coming as expected.
Controller
[HttpPost]
public IActionResult Index(string mainFin, string actNumber, int actTypeId)
{
int userId = Int16.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
Act act = new Act()
{
ActTypeId = actTypeId,
CreateDate = DateTime.Now,
ApproveDate = null,
UserId = userId,
StatusId = 1,
};
_unitOfWork.ActRepository.Add(act);
_notyf.Success("Arayış əlavə edilid !");
_unitOfWork.Complete();
return RedirectToAction("Marriage");
}
AJAX
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
},
error: function () {
console.log("------");
}
});
e.preventDefault();
$("#questForm1").submit();
});
});
Problem : When I click submit button data inserts twice to database (AJAX makes 2 request at same time )
If you want to submit the form via AJAX then you need to remove the last line of the click event handler.
$("#questForm1").submit();
This line is submitting the form and essentially negating the e.preventDefault() above.
You are submitting your data twice: at first using ajax and after that using using the form submit.
You have to remove one of them, I would guess the form submit.
Also, since ajax is called async, if you want to do something after ajax has been called and returned successfully, you have to put the code in success section.
So the code should look like:
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
e.preventDefault();
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
// do your thing here, once the ajax requst has returned successfully
},
error: function () {
console.log("------");
}
});
// NOTICE: form submit removed
});
});
When I make ajax request to the server with breakpoint in the action method it stops on this breakpoint only the first time. After clicking for second, third etc. it goes but never stops on this breakpoint. When I change the method from GET to POST it stops every time. What is the reason for this behaviour ?
CLIENT SIDE:
$(function () {
setListAction();
});
function setListAction() {
$("li.list").on("click", function () {
alert("active");
var id = $(this).attr("file-id");
$.ajax({
type: "GET",
url: "TechAcc/ManageFile/" + id,
beforeSend: function myfunction() {
$("#loading").css("display", "block");
$("#fade").css("display", "block");
},
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
});
});
}
SERVER SIDE:
[HttpGet]
public ActionResult ManageFile(int id = 0)
{
FileModel model = null;
if (id != 0)
model = new FileModel() { File = _repository.GetFileBy(id), GetAllFiles = _repository.GetAllFiles() };
else if (Session["Model"] != null)
model = (FileModel)Session["Model"];
else
model = new FileModel() { GetAllFiles = _repository.GetAllFiles() };
return View(model);
}
if your div with id "content" has list, it will not work.
<div id="content">
if your list is here, it won't work.
...
<li class="list">...</li>
...
</div>
if your design is like that, you need to bind click event after you replace your HTML response. i.e.,
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
//adding code here.
$("div#content").find("li.list").on("click", function() {
//same above click code should come here.
//Note: this newly added code block should not come here in click.
});
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
I have a MVC4 single page website with a form. The loading of the contents is achieve with ajax. I do not know how to get the data out from JSON in C#? Here is my code:
JavaScript:
$("#subnt").click(function (event) {
event.preventDefault();
var url = "/Home/Submit";
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
})
});
});
C#:
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Please check below working code -
I have used exactly your working code -
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Then I used following JQuery to hit the above action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response);
},
success: function (data) {
if (data.Success == true)
alert(data.SomeOtherData);
}
});
});
});
</script>
<input type="submit" value="click" id="click" />
And as the output I was able to get an alert as shown below -
Easiest thing to do is use the superior json.net
[HttpPost]
public string Submit()
{
var result = new { success = true, someOtherDate = "testing"};
var json = JsonConvert.SerializeObject(result);
return json;
}
Your code is ok bu you can add debugger.and open developer tools check your data .
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
debugger;
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
No, the other way around. How to retrieve the data from the form (json).
I'm using C# asp.net mvc.
I wrote a Ajax function in my Home controller - > index.cshtml.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("getAlerts","Home")',
data: ({}),
success: function (data) {
$('#alertList').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
</script>
this is my function in Home controller
public IList<tblInsurance> getAlertsIns()
{
var query = (from i in db.tblInsurances
where i.status == true && i.EndDate <= DateTime.Today.AddDays(7)
select i).ToList(); ;
return query;
}
public string getAlerts()
{
string htmlval = "";
var InsExpirList = getAlertsIns();
if (InsExpirList != null)
{
foreach (var item in InsExpirList)
{
htmlval += item.tblContractor.Fname + " " + item.EndDate + "<br />";
}
}
return htmlval;
}
But ther is error and it says " The resource cannot be found."
POST http://localhost:49368/Home/getAlerts 404 Not Found
what is wrong with my code?
If you want your controller action to accept POSTs, you must decorate it with an attribute specifying that fact:
[HttpPost]
public string getAlerts()
{
// ...
}
In this case, however, it seems like a GET request would be more appropriate (your action is called getAlerts after all). If that's the case you can omit the accepted verb, or use [HttpGet] instead. You would also have to change your AJAX request:
$.ajax({
type: 'GET',
dataType: 'html',
url: '#Url.Action("getAlerts","Home")',
/* ... */
});