I Have a Messaging web application whose conversation page needs to check for a new message at a fixed interval (say 10 sec) and refresh itself if any new message available. I don't want to put a static HTML refresh as it causes page to reload even if no new message is there !
Any help is widely appreciated !!
You could try something like this:
(function($)
{
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#content').hide();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
$('#content').show();
},
success: function() {
$('#loading').hide();
$('#content').show();
}
});
var $container = $("#content");
$container.load("page.php");
var refreshId = setInterval(function()
{
$container.load('page.php');
}, 9000);
});
})(jQuery);
Related
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
});
});
My full Calendar show data correctly using ajax . so i want to change the data on previous button click. But the button click function not working and how can i pass the data as parameter on previous and next button click
<script src="../assets/global/plugins/fullcalendar/lib/moment.min.js"></script>
<script src="../assets/global/plugins/fullcalendar/lib/jquery.min.js"></script>
<script src="../assets/global/plugins/fullcalendar/fullcalendar.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "attendance-full.aspx/GetEvents",
dataType: "json",
success: function (data) {
$('div[id*=calendar1]').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: $.map(data.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.title = item.EventName;
return event;
}), eventRender: function (event, eventElement) {
if (event.ImageType) {
if (eventElement.find('span.fc-event-time').length) {
eventElement.find('span.fc-event-time').before($(GetImage(event.ImageType)));
} else {
eventElement.find('span.fc-event-title').before($(GetImage(event.ImageType)));
}
}
},
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
$('div[id*=calendar1]').show();
//below code not working
$(".fc-prev-button span").click(function () {
alert("Hai");
})
});
My console is error free .
$(".fc-prev-button span").click(function () { runs before your calendar is created (because you wait to create the calendar until ajax has run, and ajax is asynchronous). Therefore there is no button for your code to bind the event to.
Simply move
$(".fc-prev-button span").click(function () {
alert("Hai");
});
to the end of your ajax "success" function.
N.B. I would also suggest that you re-consider how you're getting your events. Currently you fetch all events into the calendar, and the calendar cannot be displayed until the events are fetched. If your application is live for a long time, and builds up a lot of historical events, consider what will happen after a few years when there is a long list of events - it will take a long time to load them all, with no calendar on screen, and unless your situation is unusual, then probably no-one will look at anything from a long time ago, so it's a waste of time to load them.
FullCalendar is actually designed to work in a way that fetches only the events that are needed for the view and date range currently being displayed. So you fetch the minimum required events. If the user changes the view or date to something else, fullCalendar requests more events from the server, and sends it the date range required. This is usually much more efficient.
In your case you could re-write it something like this snippet below. Bear in mind you'd also have to change your GetEvents server method so that it filters the list of events by the dates supplied. I can't see that code so I can't advise exactly what you would need to do, but hopefully it will be fairly simple to add a couple of extra parameters and add a clause to your database query to compare the dates.
$(document).ready(function() {
$('div[id*=calendar1]').show();
$('div[id*=calendar1]').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: function(start, end, timezone, callback) {
$.ajax({
type: "POST",
contentType: "application/json",
data: '{ "start": "' + start.format("YYYY-MM-DD") + ', "end": ' + end.format("YYYY-MM-DD") + '}',
url: "attendance-full.aspx/GetEvents",
dataType: "json",
success: function(data) {
var events = $.map(data.d, function(item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.title = item.EventName;
return event;
});
callback(events);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
},
eventRender: function(event, eventElement) {
if (event.ImageType) {
if (eventElement.find('span.fc-event-time').length) {
eventElement.find('span.fc-event-time').before($(GetImage(event.ImageType)));
} else {
eventElement.find('span.fc-event-title').before($(GetImage(event.ImageType)));
}
}
},
});
$(".fc-prev-button span").click(function() {
alert("Hai");
});
});
See https://fullcalendar.io/docs/event_data/events_function/ for more details of the event feed function.
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
};
})();
I am using a jQuery jTable and it gives the message first "No Data Available" before it loads the data and displays a long list of it. So is it possible to display an Ajax loader (loading.gif) first while it's loading the data in the background?
Edit #Rex: i Tried this but don't know how to implement it with the jQuery jTable success function.
This is the code I tried:
$(document).on('click', '#PlayStatisticone', function (e) {
function loadingAjax(div_id) {
var divIdHtml = $("#"+div_id).html();
$.ajax({
url: '#Url.Action("_TopPlayedTracksPermissionCheck", "ReportStatistic")',
type: 'POST',
beforeSend: function() {
$("#loading-image").show();
},
success: function (data) {
$("#"+div_id).html(divIdHtml + msg);
$("#loading-image").hide();
$(function () {
$("#PartialViewTopPlayedTracks").load('#Url.Action("_PartialViewTopPlayedTracks", "ReportStatistic")');
});
},
error: function (xhr, textStatus, exceptionThrown) {
var json = $.parseJSON(xhr.responseText);
if (json.Authenticated) {
window.location.href = '/UnAuthorizedUser/UnAuthorizedUser';
}
else {
window.location.href = '/UnAuthenticatedUser/UnAuthenticatedUser';
}
}
});
Any suggestion would be really helpful
Thanks in advance.
It worked just as I wanted... I found it from an another forum
I don't know if it's ok to post worked answers from another forum or not in here:
here's the code that worked:
$(document).ready(function () {
// DOM is ready now
$.post("<%= Url.Action("ActionThatGetsTableOnly") %>",
"",
function(data) { $("#elementToReplaceId").html(); },
"html"
);
});
I am using ASP.NET MVC in C#
I have a page where the user can move different Widgets around the page, and I now need a method to save the state of the widgets. I am using jQuery in the HTML page, and the jQuery posts the new page layout using JSON. I am unsure how to read the JSON in the controller.
The code I'm using is based on this example here - http://webdeveloperplus.com/jquery/saving-state-for-collapsible-drag-drop-panels/, but the code for saving the result is in PHP.
jQUERY
<script type="text/javascript" >
$(function () {
$('.dragbox')
.each(function () {
$(this).hover(function () {
$(this).find('h2').addClass('collapse');
}, function () {
$(this).find('h2').removeClass('collapse');
})
.find('h2').hover(function () {
$(this).find('.configure').css('visibility', 'visible');
}, function () {
$(this).find('.configure').css('visibility', 'hidden');
})
.click(function () {
$(this).siblings('.dragbox-content').toggle();
//Save state on change of collapse state of panel
updateWidgetData();
})
.end()
.find('.configure').css('visibility', 'hidden');
});
$('.column').sortable({
connectWith: '.column',
handle: 'h2',
cursor: 'move',
placeholder: 'placeholder',
forcePlaceholderSize: true,
opacity: 0.4,
start: function (event, ui) {
//Firefox, Safari/Chrome fire click event after drag is complete, fix for that
if ($.browser.mozilla || $.browser.safari)
$(ui.item).find('.dragbox-content').toggle();
},
stop: function (event, ui) {
ui.item.css({ 'top': '0', 'left': '0' }); //Opera fix
if (!$.browser.mozilla && !$.browser.safari)
updateWidgetData();
}
})
.disableSelection();
});
function updateWidgetData() {
var items = [];
$('.column').each(function () {
var columnId = $(this).attr('id');
$('.dragbox', this).each(function (i) {
var collapsed = 0;
if ($(this).find('.dragbox-content').css('display') == "none")
collapsed = 1;
//Create Item object for current panel
var item = {
id: $(this).attr('id'),
collapsed: collapsed,
order: i,
column: columnId
};
//Push item object into items array
items.push(item);
});
});
//Assign items array to sortorder JSON variable
var sortorder = { items: items };
//Pass sortorder variable to server using ajax to save state
$.post('/Widgets/SaveLayout', 'data=' + $.toJSON(sortorder), function (response) {
if (response == "success")
$("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000);
setTimeout(function () {
$('#console').fadeOut(1000);
}, 2000);
});
alert(sortorder);
}
I am willing to consider alternative ways to do this, as I may not have chosen the best way to do this.
Phil Haack's blog post http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx specifically handles the problem you are trying to solve and it works great.
Hope this helps.
Why not use a cookie? This would save you from having to pull that data back and forth from the server so much.