I Want to execute a function when the page load but don't know how to do it. cause that I have a list but his data from to another place in the load.
It sounds like you are refreshing page content through an AJAX call and you want to make that AJAX call on the page load in ADDITION to binding it to an event.
Assuming that is the case, at the end of your ModelViewModel declaration, simply call the function. For example:
function SearchResultsViewModel(){
this.updateResults=function(){
//Some AJAX Call and action.
}
this.updateResults();
}
You bind the knockout viewmodel to the view as normal, then use
window.onload = function ()
{
//data from to another place in the load
}
or in jQuery
$(document).ready(function(){
//data from to another place in the load
)};
Since knockout is bound to the view, when you add items, the view will update automatically.
Related
I use asp.net razor and I load part of page in a partial view by Jquery load function. Part of script in the partial view is a JavaScript event like this:
$("#FormId").on("submit", function () {
//doSomeThing..
//ajax request ..
$("ContainerDivId").load("UrlToAction"); //load partial view in ajax success function
});
The problem is event create by every load and bind to another handler in another chrome VM file so handler function call several times by click on submit button.
I solved the problem by a flag variable but I know there is a clean solution. Where did I go wrong?
Change your code that adds the event handler to remove the old one first:
$("#duplicateFacilityForm").off("submit").on("submit", function ...);
I'm new to ajax and want to best understand how to write my jQuery code so that then a page is called via ajax, my jQuery functions (simple stuff like slideshows and overlays) will still work.
Below is what I'm currently doing to make my jquery work on a stand alone page without ajax.
$('.microContentWrap').click(function(){
//perform some functions
});
In order to make this same function work when this page has been loaded via ajax, I'm duplicating my code and binding it to a div called "ajax-wrapper" that loads normally on this page. Without this step, the above code was not executing on the ajax page.
$("ajax-wrapper").on("click", ".microContentWrap", function() {
//exact same functions as above
});
Both of these things work, but is this the most efficient way? Seems repetitive to do this two step process for every single function in my file.
$("ajax-wrapper").on("click", ".microContentWrap", function() {
//exact same functions as above
});
Is saying: "when I click within 'ajax-wrapper' check to see if the element I clicked is 'microContentWrap', if it is, then do this function". The benefit of this approach is that 'microContentWrap' doesn't need to exist when you bind the click even listener.
Another approach would be to add the event listener to 'microContentWrap' in your ajax callback function. So for example:
$.ajax({
url:"getvalue.php",
success:function(data) {
$('body').append('<div class="microContentWrap"></div>');
$('.microContentWrap').click(function(){});
}
});
The solution to this was actually very simple, I just didn't understand binding. The problem I was having was that the ajax-wrapper gets destroyed after the microContent comes in. On other non-ajax pages there was no ajax-wrapper which is why I thought there needed to be two functions. By binding to the body, I eliminated the issue.
$("ajax-wrapper").on("click", ".microContentWrap", function() {
//exact same functions as above
});
I'm using jQuery for a small project I have and it's one of my first times using it. Is it safe to put all my UI code in $(document).ready() ? I'm basically creating a form that pops up when a button is pressed, and the form is processed via AJAX. Basically, when I separate my AJAX function from the functions controlling the UI, the AJAX doesn't work. However, when I put both of them in $(document).ready(), everything works fine. Here's my code. Please ignore my comments, as they were for learning purposes.
$(document).ready(function(){ //ready for DOM manipulation
/*FORM UI*/
var container_form=$('#container_form'); //container form box
var addButton=$('.addButton'); //"+" add button
container_form.hide(); //initially hides form
$(addButton).click(function(){
$(container_form).toggle('fast');
/*SUBMISSION AJAX*/
$('form.ajax').on('submit',function() { //Make form with class "ajax" a JQuery object
var that = $(this), //"that"-current form, "url"-php file, "type"-post, "data"-empty object for now
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){ //search all elements in the form with the attribute "name"
var that=$(this), //legal attribute
name=that.attr('name'); //name of the legal attribute
value=that.val(); //value of text field in legal attribute
data[name]=value; //data object is filled with text inputs
});
$.ajax({
url: url, //url of form
type: type, //type of form
data: data, //data object generated in previous
success: function(response){ //reponse handler for php
if(!response){
console.log("Error");
}
console.log(response);
}
});
return false; //Stops submission from going to external php page.
});
});
});
Generally any selectors such as $('form.ajax')., $('#container_form'), $('.addButton') needs to be in doc.ready to ensure that the DOM is ready before you try to select an element from it, since it may not find the element if the DOM hasn't finished processing. So that pretty much applies to all of your code. If you had a function such as this:
//defines a function
function addThem(first,second)
{
return first + second;
}
You could declare it outside of doc ready, and call it from within doc ready.
$(document).ready(function(){
$('#someInput').val(
addThem( $('#anotherInput').val() , $('#thirdInput').val() )
);
});
The way I think about this, is doc ready is an event, so you should be doing things in response to the "document is now ready for your to query event", not declaring things. Declaring function just says what that function does, but doesn't actually do anything, so it can go outside of the document ready. It'd be pretty silly to declare this function inside of doc.ready since it can be defined at anytime (although it certainly is possible to put it inside doc ready, it just generally clutters things up). Even if it were selecting an element, that code isn't actually running until it is called:
function hideContainer()
{
//this code never runs until the function is called
//we're just defining a function that says what will happen when it is called
return $('#container').hide();
}
$(document).ready(function(){
//here we are calling the function after the doc.ready, so the selector should run fine
hideContainer();
});
Note that the act of wiring up to other events is an action in itself, such as when you subscribed to the click events and form submit events. You are saying, "find the form element with class .ajax, and subscribe to its submit event". You wouldn't want to try and wire up to events of DOM elements until the DOM is done processing. They might not "exist" yet as far as the browser is concerned if it is in the middle of processing the DOM, and thus your attempt to wire up to the click/form submit events may fail. I say may because depending on timing/processing lag it may sometimes work and sometimes not.
There's not only nothing wrong with putting all your code into one $(document).ready(), but there's nothing wrong with putting it into multiple $(document).ready() functions either so that you can separate repeated functionality into individual JS files.
For example, I use $(document).ready() in a script included on all my site's webpages to set up UI elements, prevent clickjacking, etc. At the same time, each page regularly has its own $(document).ready() which sets up page specific user interactions.
It is absolutely OK. If you find yourself needing to abstract your code into multiple function or multiple files, then by all means, but there's nothing wrong with throwing everything in $(document).ready().
I have a simple custom tabbing module, that loads tabs with an AJAX request (via $(elem).load()). On each page that is loaded with AJAX I have some JavaScript. The first time the page loads (via direct input of URL, not AJAX), the javascript fires up perfectly. When I navigate away from the page via the AJAX tabs, the javascripts from the pages aren't loading anymore.
Is there any way I can force them to execute?
(The javascript that is not firing is placed in a $(document).ready() function if that helps)
You need to use callback of load() function:
$(elem).load('source.html', function() {
// here you need to perofrm something what you need
ActionOnDocumentReady();
});
You can put all your actions in $(document).ready into some function (ex ActionOnDocumentReady()) and call it on load() callback.
the domeready event fires only when is initial dom is ready (like the name and the jquery-api suggest).
if you want to use jquerys load() and fire a function if that loading has been done, you'll have to use a callback-function (according to the api).
if you want to do the same thing on domready and load-events, the best way would be to define a new function for that:
function dostuff(){
// do some stuff here
}
and fire this function in both cases:
$(function(){ // domready | shortcut for "$(document).ready()"
dostuff();
})
$('#something').load('script.php', function() { // callback on load()
dostuff();
});
Put your $(document).ready() code in a new method. Lets call it methodA. Now call this methodA from $(document).ready(). Secondly, call the same method after ajax request is successful. That should solve your problem.
I am currently having trouble with the following (here is some sample code first):
<div id="container"></div>
<script type="text/javascript">
$('#container').load('content.html');
$('.elementInContentHTML').fadeIn();
</script>
In short, I want to be able to access elements that have been dynamically added to a page without attaching them to event handlers.
I know about the live() method, but I do not want to bind my action to any event, i.e. I just want to run some actions with these new elements without clicking them, focusing, blurring, etc.
The load function is asynchronous.
Your next line runs before the content is loaded.
You need to put your code inside the load function's callback, so that it will only run after the new content is loaded:
$('#container').load('content.html', function() {
$('.elementInContentHTML').fadeIn();
});
You could try using the callback for when load completes? See http://api.jquery.com/load/
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});