all JQuery functions lost on partial postback - javascript

I have an aspx page (the JQuery.js is called in the masterpage for this). Now this is linked to the http://code.jquery.com/jquery.js
In this page I have an updatepanel which is dynamically loading different usercontrols which in turn have their own JS files loads (using scriptmanager). Now on a partial postback I am losing JQuery functions (for instance .val returns undefined).
[code]
function pageLoad(){
//whatever you want to do on partial postback
//alert('partial handler');
$(jutb).watermark('Username or Email address');
$(jptb).watermark('Password');
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
// Called when async postback begins
function InitializeRequest(sender, args) {
// alert("You are in the InitializeRequestHandler function."); // breakpoint here
}
// Called when async postback ends
function EndRequestHandler(sender, args) {
// this function is run after an Ajax partial postback occurs
loadUsername();
loadPassword();
if (args.get_error() != undefined)
alert("There was an error" + args.get_error().message);
return;
}
[/code]
my page load is being called in the partial postback. (i.e. I can alert to it.)
I have a linkbutton which triggers some JS code. after the partial postback if I try it .val returns undefined.
Any ideas why JQuery is being lost?

When you get the response back from the server into your update panel, all event handler bindings you did the first time the page loaded are broken, because those are new elements now, even though they satisfy the same selection criteria.
You can try to re-run your event handler binding - you can create some kind of init JS function that you'd call in your EndRequestHandler.
Other way, and probably better, would be to use jQuery's on to bind your elements to event handlers. Take a look here on how to use it:
https://api.jquery.com/on/

Related

How to run a Javascript/Jquery Function using both $(document).ready(function() and Another Event Function?

I'm not a javascript/jquery coder, and not sure if what I'm trying to do is possible.
I have a html/php/ajax form that is updated an sql database as the user fills it out. As they fill the form, there is a progress bar ran by javascript/jquery that updates as the user types in the input. The start of the function looks like this:
$("#update input").keyup(function() {
This works great. My problem is when the page is reloaded. My code is pulling sql data from the database to fill the value of every input on the page that has a value so that a user can come back and completely the form later. When the user reloads the page, the only way for the script to activate is if the user types in an input field.
I thought I would fix the issue by changing the my initial javascript/jquery function with $(document).ready(function() . This caused the script to only run when the page was loaded and not when the form was being filled out. I need both the script to run on page ready, and when a user is typing in the input filled. Is there a way I can run both $(document).ready(function() AND $("#update input").keyup(function() { simultaneously? Or is there a better why to accomplish this? Thanks!
Let me know if I need to post more code.
Here's a generic approach attaching declared functions to events.
function handler (e) {}
element.addEventListener('click', handler);
You're free to call handler everywhere, also inside $(document).ready, or if there's no other code in your DOMReady handler, you can just pass a reference as an argument:
$(document).ready(handler);
In your specific case you most likely want something like this:
$(document).ready(function () {
function handler (e) {...}
handler();
$("#update input").keyup(handler);
});
If the handler function uses the event object (e in the example), in modern browsers it's also available as a global event object, or in jQuery, e.originalEvent. The object doesn't exist if there's no event fired, though, in that case you've to pass a fake event object, containing the provided properties, to the handler, if it is needed.

Does submit() on a form block?

I am running the following code which is:
iframedoc.getElementsByTagName('form')[0].submit();
I need to execute code as soon as the form is done being submitted. Does the submit() block, or do I need some other way to determine when the form has been submitted?
No, triggering a form submit does not block or return anything useful. It merely tells the browser to create a request which will render a new page. However, with an iframe the onload event can be used to handle the response from the form submit after it has loaded.
iframedoc = iframe.contentDocument;
iframe.onload = function(e) {
alert('frame loaded');
// read its url, content, etc...
};
iframedoc.getElementsByTagName('form')[0].submit();
// immediately returns undefined and your code proceeds
Since JavaScript runs in a single thread, you won't see the 'frame loaded' alert until all of your subsequent code has completed, the browser submits the form, and the onload event triggers.

Automatic onsubmit handler in loop

I have the following problem with Javascript.
I'm trying to add an "onsubmit" handler automatically (after the page has been loaded) to every form element in the page.
So I wrote this script:
window.onload=function(){
var formElements=document.getElementsByTagName("form");
for (var k=0;k<formElements.length;k++){
formElements[k].onsubmit=function(param){
return formValidator(param);
}(formElements[k]);
}
};
The formValidator function takes a form object as parameter, validates the content of the input and textarea elements inside the form and returns true or false as results of the validation.
In the HTML file of the page I have a form element without the onsubmit attribute (that should be inserted by javascript).
The problem is that it seems that the form is automatically validated when the page is loaded (even if the user doesn't submit the form). And then if the user starts to insert data in the form and clicks the submit button the validateForm function doesn't execute.
Any ideas?
Thank you.
You're calling your handler function, and assigning the result of calling it to onsubmit. (The (formElements[k]) after the function calls it.)
You need to refer to the function without calling it. One good way to do that in the general case is to use a builder function (but see below for why that general case probably doesn't apply here):
window.onload=function(){
var formElements=document.getElementsByTagName("form");
for (var k=0;k<formElements.length;k++){
formElements[k].onsubmit=buildHandler(formElements[k]);
}
function buildHandler(form) {
return function(){
return formValidator(form); // <== I'm guessing `formvalidator` takes the form
};
}
};
But there's no need to create a separate handler for each form. The way you're assigning the handler, this will be the form element, so just:
window.onload=function(){
var formElements=document.getElementsByTagName("form");
for (var k=0;k<formElements.length;k++){
formElements[k].onsubmit=handler;
}
function handler(){
return formValidator(this);
}
};
The thing about this being the element will be true when you assign functions to onxyz properties on DOM elements, when you use attachEvent (on IE), or when you use addEventListener (standard). It is not true if you call a function from onxyz attributes in the markup, e.g. onsubmit="foo()" (although you can use onsubmit="foo.call(this);" and it will be).

Call JavaScript function when button loaded by ajax is clicked

I have an html form that loads its contents through ajax and includes buttons that, when clicked, should execute a JavaScript function that is defined in the html page's script tag. SO: Button is loaded through ajax (works), but when button is clicked, it doesn't trigger the desired action and doesn't trigger a JavaScript error in Firebug. How does one get the onclick signal of a bunch of buttons loaded through ajax to bind to an already existing JavaScript function?
EDIT: I should have noted also that I am not using JQuery. I am willing to do so if it is the only way, but otherwise, I would prefer to use only native JavaScript.
EDIT2: My problem was a bit more involved, but as was stated in the chosen answer, you should be able to set the onclick event handler in the php script before sending the data through ajax. If you have a data-heavy response and want to reduce bandwidth, you might consider doing everything client-side, but I find it easier in most situations just to set the onclick attribute in the php script.
Your dynamically generated button could have an inline event bound to it. When generating the button, simply make sure it has an onclick="alreadyExistingFunc();" and the page will happily execute it.
Alternatively, when your AJAX data is finished writing itself into the document, find the new button(s) and bind the event to them:
function ajaxSuccess()
{
document.getElementById('newButtonIdHere').onClick = function() {
alreadyExistingFunc();
}
}
That should do the trick. Also note that if you ever "need" a small part of jQuery to do something (like selectors or event handling), you can almost always do it without loading the whole library.
Append/insert the HTML (retrieved AJAX response) to DOM and bind click event to it:
function alreadyExistingFunc() {
alert('button is clicked!');
}
var ajax_data ="<button id='my-button'>My Button</button>";
$('body').append(ajax_data).find('#my-button').on('click', function(e){
alreadyExistingFunc();
// some more code...
});
OR:
$('body').append(ajax_data).find('#my-button').on('click', alreadyExistingFunc);
You could also use a callback:
function getAjaxContent(callback) {
$.ajax({url: "url"}).done(function() {
callback(data);
});
}
getAjaxContent(function (data) {
//ajax content has been loaded, add the click event here
}

Call javascript from asp.net mvc

How can i call a javascript function from a mvc controller similar
to what you would do in webforms with ICallbackHandler?
Is it possible?
Thank you.
Controller actions cannot call javascript functions. They return action results. Javascript code should be contained on the client side. So if you want to call a javascript function that should execute under certain circumstances you could subscribe for the corresponding event and when this event is triggered call the function.
For example if you wanted to call a javascript function when a button is clicked using jQuery you could do the following:
$(function() {
// subscribe for the click event
$('#someId').click(function() {
// the button is clicked => execute some javascript function here
});
});

Categories

Resources