JQuery: How do you use live with the post function - c#

When load the new html from a post function I lose all of my click bindings. I read that i could use live to keep all the bindings but can't find any examples where live is used with post. Here is my code:
$('.GroupHeader').unbind('click').live('click', function (event) {
event.preventDefault();
TemplateEditor.SelectGroupClicked($(this));
});

You should use live to bind your click event handlers, i.e.:
$(selector).live('click', function () {
//...
});
Instead of :
$(selector).click(function () { // or $(selector).bind('click', ...
//...
});
In that way, doesn't matter your elements are replaced, the events will still work, because live works with event delegation.

Related

Click event not posting to handler

I'm playing with JQuery, and I'm trying to fire a Click event on a button, to run off to a handler in my asp.net application, and getting some strange results.
I'll post the code and then explain whats happening :-
$(function () {
$("[id$='btnClaimValidate']").click(callSwapClaimHandler);
function callSwapClaimHandler() {
$.ajax({
type: 'POST',
url: "/handlers/investor-tickets/claimswapvalidator.ashx",
data: {
investorId: $("[id$='hdnInvestor']").val(),
investorTicketId: $("[id$='hdnInvestorTicket']").val(),
originalClaimId: $("[id$='hdnInvestorTicketClaimId']").val(),
newClaimId: $("[id$='txtClaim']").val()
},
dataType: "html",
error: function () {
alert("failure");
},
success:
function (data) {
var $newdiv = data;
$("[id$='divMessageData']").append($newdiv);
}
});
}
});
With the code above, the handler is never called. The event is 100% being fired on click. I've tested by removing the ajax post function, and replaced it with a simple alert("Hello); command to be sure.
What is strange is that if i register the click event to actually execute on DOM load by doing this :-
$("[id$='btnClaimValidate']").click(callSwapClaimHandler());
The handler is fired as the page loads and then works as expected.
By taking off the parenthesis, so that it is only fired on click, the post never actually executes.
I've debugged the browser session, and the function runs, but it never gets to the handler, and no content is returned.
Can anyone explain what's going wrong?
Your comment to #Scarface Ron is the clue. Your page is refreshing as the default button behavior was not stopped. Also just use the function inline in the handler:
$(function () {
$("[id$='btnClaimValidate']").click(function (e) {
// Stop the button actioning!
e.preventDefault();
$.ajax({
type: 'POST',
url: "/handlers/investor-tickets/claimswapvalidator.ashx",
data: {
investorId: $("[id$='hdnInvestor']").val(),
investorTicketId: $("[id$='hdnInvestorTicket']").val(),
originalClaimId: $("[id$='hdnInvestorTicketClaimId']").val(),
newClaimId: $("[id$='txtClaim']").val()
},
dataType: "html",
error: function () {
alert("failure");
},
success:
function (data) {
var $newdiv = data;
$("[id$='divMessageData']").append($newdiv);
}
});
});
});
apologies if I got the closing braces wrong here
The simple explanation here is that your button selector - [id$='btnClaimValidate'] - isn't matching anything at the time it is executed. Hard to say why (you're generating that part of the DOM after the page is loaded? You have a typo?) but you can test this easily enough:
$(function()
{
alert($("[id$='btnClaimValidate']").length);
});
If the value is 0, then this is your problem and you'll have a specific area to investigate further.
Alternately, use your browser's DOM inspector to verify that an event has actually been attached to the button after the load has completed.
If the problem is simply that the button is added to the DOM after the page is loaded, then you might want to consider using a delegated event instead of attaching the handler directly to the button. For instance:
$("document").on("click", "[id$='btnClaimValidate']", callSwapClaimHandler);
This will attach the event to the document (which exists) but mandate that the handler is only called when the event has bubbled up from the button (which may not exist yet when the handler is bound, but probably will later).

Delaying Calling JQuery or javascript method from c#

I've got a mixture of JQuery and Ajax partial postbacks on a webforms page and I'm trying to stop the user navigating away from a page without their changes having been saved.
It's working pretty well unless one of the data validators on the page is invalid. There is a jquery method on the submit button that basically nulls the onbeforeunload event. In the event that the validators are invalid, I dont want that to happen, so I turned off the client side validation, and in the method, called Page.Validate(), then if the page was invalid, I tried to register a startup script as described here to reset like so:
if (!Page.IsValid) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "setConfirmUnload(true);", true);
return;
}
If I run the click submit and the page is invalid, the call to setConfirmUnload(true) happens, but the method cant be found (presumably because I re-set this up every time a postback happens?
The actual error is " JavaScript runtime error: 'setConfirmUnload' is undefined", possibly because the bindEvents() hasnt yet re-run and therefore created it?
I thnk my problem stems from the fact that I am using partial postbacks and autopostbacks, setting up data as the user modifies the form. By default that blitzes my jquery, so I rebind the jquery calls on document.ready() as well as on postback using
<script type="text/javascript">
// attach the event binding function to every partial update
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (evt, args) {
bindEvents();
});
</script>
And my Bind Events method looks like:
function bindEvents() {
// stuff removed for brevity here...
$(function () {
// Prevent accidental navigation away
$(':input, select').bind(
'change', function () { setConfirmUnload(true); });
$('.noprompt-required').click(
function () { setConfirmUnload(false); });
function setConfirmUnload(on) {
window.onbeforeunload = on ? unloadMessage : null;
}
function unloadMessage() {
return ('You have entered new data on this page. ' +
'If you navigate away from this page without ' +
'first saving your data, the changes will be lost.');
}
window.onerror = UnspecifiedErrorHandler;
function UnspecifiedErrorHandler() {
return true;
}
});
}
If that's the case, is there a way I can force the script to run after the bindEvents() call has happened?

JavaScript code to refresh page and or telerik grid

I need some kind of code which will refresh the page every 5min and if not the page then just the Telerik grid displayed on it since that's all that's rly needed.
Only other thing would be if it was after 5min of no activity on the page if possible but it's not core feature.
One possibility is to use a meta refresh tag:
<meta http-equiv="refresh" content="300" />
Another possibility is to use the window.setInterval method to send periodic AJAX requests to a controller action and update the DOM:
window.setInterval(function() {
// Send an AJAX request to a controller action which will
// return a partial with the grid and update the DOM
$.ajax({
url: '/grid',
success: function(result) {
$('#someGridContainer').html(result);
}
});
}, 300000);
And to implement the idle functionality you could use the jquery idle plugin.
keep it simple, call refreshGrid() function when you need to refresh grid.
function refreshGrid() {
if ($(".t-grid .t-refresh").exists()) {
$(".t-grid .t-refresh").trigger('click');
}
}
/*return true if does selected element exist.*/
(function ($) {
$.fn.exists = function () { return jQuery(this).length > 0; }
})(jQuery);
setTimeout(function(){
window.location.reload();
},300000);
If your grid is set up for ajax refreshes, then you can use something like
<script type="text/javascript">
$(function() {
setInterval(function() {
$('#GridName').data('tGrid').ajaxRequest();
}, 300000);
});
</script>
For Server Bindings Telerik Grid Just need to do the following Thing..... Just use and cheers
After any event you can call this
var href = $('.t-refresh').attr('href');
window.location.href = href;
If you are using Ajax or Webservice binding on the Telerik Grid, you can call the rebind() method on the grid object. That will force it to call the Select method of the binding again to get the latest data.
If you combine the rebind() call with Darin's answer of using the SetInterval method, it should give you what you are after.

JQuery causing postback in .NET

I created an adrotator in jquery for the first time and when I use it on a page that uses pagemethods to do ajax calls to the server and show a modal. The page posts back. When I remove the rotator the page works as it should. In the rotator I have the following code in the document ready function.
$(".animation_control a.play").live('click', function () {
$(this).removeClass('play');
$(this).addClass('pause');
Play();
});
$(".animation_control a.pause").live('click', function () {
$(this).removeClass('pause');
$(this).addClass('play');
clearInterval(timer);
});
$(".animation_control a.pause").click(function () {
});
//Toggle Teaser
$("a.collapse").click(function () {
$(".main_image .block").slideToggle();
$("a.collapse").toggleClass("show");
});
If I comment out this code the page stops the complete page refresh and and posts back async like it should. Any ideas on why this would cause the page to do a complete postback instead of a partial one?
As a guess, since the code is incomplete, you should add return false to your event handlers to prevent the links from actually firing.
.live('click', function (e) {
e.preventDefault();
//your code
Anchors are used to navigate to a page/region in the same page, and according to this part, clicking an anchor MUST move us to the HREF that the anchor is pointing to.
in order to cancle this default behavior, we will need to do either return false or to prevent the default action using jQuery.
This is an example of what i mean.

Javascript event on page postback

Is there any javascript event which is triggered on postback?
If not, how can I run client side code immediately after or before a page postback?
I believe what you are looking for is the Sys.WebForms.PageRequestManager beginRequest Event
Excerpt:
The beginRequest event is raised before the processing of an
asynchronous postback starts and the postback is sent to the server.
You can use this event to call custom script to set a request header
or to start an animation that notifies the user that the postback is
being processed.
Code Sample: (From the link)
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args)
{
var elem = args.get_postBackElement();
ActivateAlertDiv('visible', 'AlertDiv', elem.value + ' processing...');
}
function EndRequestHandler(sender, args)
{
ActivateAlertDiv('hidden', 'AlertDiv', '');
}
function ActivateAlertDiv(visstring, elem, msg)
{
var adiv = $get(elem);
adiv.style.visibility = visstring;
adiv.innerHTML = msg;
}
</script>
I hope that helps. The PageRequestManager class seems to be little known about and little utilized.
Take a look at:
Run javascript function after Postback
I solved my problem using this:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function (s, e) {
alert('Postback!');
});
</script>
there are a lot of options too, like
$('#id').live('change', function (){});
$(document).ready(function () {});
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
and keep going. depends on what you need.
PageRequestManager events: https://learn.microsoft.com/en-us/previous-versions/aspnet/bb398976(v=vs.100)
You could add the javascript in your page load like this...
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert",
"alert('hello world');", true);
OR
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertScript",
"function Hello() { alert('hello world'); }", true);
The Page.ClientScript object has a RegisterOnSubmitStatement This fires after any input submits the form. This may or may not be what you're looking for, but I've used it for notifying the user of unsaved changes in editable forms.
The advantage to using this over RegisterStartupScript is that with RegisterOnSubmitStatement, if a user navigates away and back using the browser, whatever script you've injected using RegisterStartupScript could possibly fire again, whereas RegisterOnSubmitStatement will only run if the user has submitted the form.
Use AJAX, with an event handler for the onComplete.
The onsubmit event on the form tag
When using jQuery it's like this
$("#yourformtagid").submit(function () {
...
}
There isn't a javascript event triggered when a page loads after a postback, but you can add javascript to your html template (.aspx file) and only run it if the page was posted, like this:
<script type='text/javascript'>
var isPostBack = '<%= this.IsPostBack%>' == 'True';
if (isPostBack) {
alert('It's a PostBack!');
}
</script>
If you want to customize the javascript to run only under particular conditions (not just any postback), you can create a page-level variable (protected or public) in your page's class and do something similar:
var userClickedSubmit = '<%= this.UserClickedSubmit%>' == 'True';
if (userClickedSubmit) {
// Do something in javascript
}
(Nothing against ClientScript.RegisterStartupScript, which is fine - sometimes you want to keep your javascript in the page template, sometimes you want to keep it in your page class.)

Categories

Resources