Jquery Document.ready when loaded through AJAX links - javascript

I am new here, so please pardon any beginner mistakes.
I am learning jQuery (v1.9.1) along with using jQuery Mobile (v1.3.1). I am encountering two problems when using AJAX links and javascript:
1) When I link pages through the default AJAX linking method that jqm offers, I lose the capability of running any newly loaded javascript on the subsequent pages. i.e. When I go from page1.php to page2.php, can I execute javascript namely something like the following (this code is in page2.php):
<script>
$(document).ready(function(){
$('#form_field_email').focus();
});
</script>
After browsing through bunch of questions here, I believe it is because no new script is evaluated after initial page load. Therefore, I tried to move all my code into on .js file, which I load on page1.php. But sometimes I want to trigger actions on-page-load (as noted above).
Is there any way to achieve this without using eval function?
2) On a similar note, if the id of a DIV on page1.php was 'messageBox', but if I use the same id for another DIV on page2.php, I lose the capability of controlling the newly drawn DIV on page2 as the javascript still points to the old DIV which is no longer visible.
$('#messageBox').show();
Is there a way to use the same name but still be able to point to the elements on the current page.
Thank you for your help.

What you should do is place the code that needs to run after the ajax has loaded in a success callback for the ajax call.
$.ajax({
url: 'http://example.com',
success: function() {
//do something when call completes successfully
}
);

Related

Javascript onload after redirect

in my Javascript code I am loading a page, and then would like to perform some functions. I tried to use solutions like window.onload, but that is after my html (blank page with just the JS) loads, I need the function to perform after the page I am reffering to is loaded.
I am using this code:
this.document.location.href = myurl;
And after this loads, I would like to call some function. Is there a way to do so?
Thanks
EDIT:
I can not edit the target page source code.
When you change the value of document.location.href, you are essentially doing a redirect.
You can either just do whatever you want to do within the loaded page itself or if you don't have cross domain issues, do xhr of the page you're wanting to load dynamically, query the body, replace content of your current body and also replace head contents i.e. style, title and scripts etc. You could then execute any script you want.
Extra note: This is quite a tricky thing to do, I've done this a few times before - and its proven quite problematic due to the fact that you don't actually get a fully parsed document object that you can just query so simply, you only receive a huge string. One hack that I've thought of using is actually just loading everything within an iframe allowing easy querying which is actually documented - extra reading here
window.load takes forever to fire because it waits for all images and assets to load on the page.
It sounds like the best solution for you would be to poll for the document to be finished loading. Here's a simple example:
(function poll(){
if(document.readyState === "complete"
{
// Your code here
}
else
setTimeout(poll,500);
})();
Place the 'window.onload = myFunction(){...}' inside the page, which will be loaded.
this.document.location.href
will open the page like you typed it into the browser address bar and your onload-script in the old page will not be executed in the new one.
By the way, you can shortcut it to document.location = myUrl
See the Document-API at Mozilla

How to dynamically include a html file containing javascript

in my website i have a simple navigation bar where clicking on the different items causes the main content to change. Technically, all is done in a single file "main.html", which contains everything and i use the jquery function "load" to dynamically load other html files to place it inside the main.html. This works just fine as long as there is no javascript in these html files i embedded. But there is one file i want to embedd, which has also javascript code in it, which should get executed on $(document).ready. But this never happens - there is no error in the javascript, it just never gets executed. I suppose it's because i only change the DOM of the "main.html" and then there will be no "onReady" event fired. Can someone give me some idea of what would be the best way to get the desired behaviour? Placing the javascript in the "main.html" would cause things to work, but this is no option for me.
Thanks in advance!
update: problem solved
Problem is solved. When i call the javascript outside the onReady() event (as Loic Coenen suggested), it works just as excpected. I also removed the tags wrapped around. Many thanks to all who helped me!
You can trigger a custom event to notify your other.html script that the tree is loaded. I haven't tried it, but I would use something like that :
In main.html:
$('#div_to_load').load('other.html',{},function(){
$('#div_to_load').trigger('loaded')
})
In other.html
$('#div_to_load').on('loaded', function(){
// Code to execute
})
I don't know if that could do the trick.
Edit : I asume that the javascript directly included in your other.html is executed anyway.
you are in main.html that contains a head, body. the problem might be that when you load the page your other page also has a head, and body and so on, if you are loading onto a div, it should be only code, can be javascript aswell, but no head or body. but if you resist, here is your solution
$("#loadnewpagebttn").load(location.href+" foobar ",function(){
$.getScript("js/yourscript.js");
});
you need to create a script file for that page and load it. inline scripts are some what of a bad habit anyways
full example:
jQuery.getScript( url, [ success(data, textStatus) ] )
url - A string containing the URL to which the request is sent.
success(data, textStatus) - A callback function that is executed if the request succeeds.
$.getScript('ajax/test.js', function() {
alert('Load was performed.');
});
http://api.jquery.com/jQuery.getScript/

loading a js file asynchronously from a js file that loads asynchronously

I had a javascript file(initial.js) on the page inserted through the script tag like so:
<script src="initial.js"></script>
This file creates dom elements(let say two links) and also loads another jQuery plugin(plugin.js) asynchronously via jQuery ajax method. Clicking on those two links brings up a module from the jQuery plugin(plugin.js).
The javascript file(initial.js) was then modified to load asynchronously on the page via jQuery ajax instead of via script tag. This has resulted in some events not getting attached to the links intermittently and this results in the plugin not being called.
I believe the browser is loading the async scripts in its own order and hence the links fail to launch the plugin intermittently. Any pointers to resolve this issue with this new set up?
At a high-level, I think you need to look into something like require.js. Alternatively, you could look into some jQuery event handling code which allows you to listen on load events of calls which may help you determine when one script loaded before loading the next one.
You have probably tried something like this in the past:
var output;
$.get('data.php',function(data){
output=data;
});
alert(output);
You will get an undefined error because Javascript doesn't wait around for the AJAX call to be returned before moving onto the next code.
Same thing goes for scripts. If you place multiple calls to multiple scripts, you will probably get the smallest one returned the quickest, and that script executed. If you load a script that is 10kb and then one that is 1kb, the 1kb script will probably return the quickest and then be executed even though it was called after the 10kb script.
To correct this, you could make a queue system and then only load each script after the previous has loaded:
var scripts=['script1.js','script2.js','script3.js'];
$(document).ready(function(){
loadScript();
});
function loadScript(){
if(sendQueue.length==0)
return;
$.getScript(scripts[0],function(){
scripts=scripts.slice(1);
loadScript();
});
}
But if you are loading scripts from within scripts from within scripts... very Inception like, then this still may not work.

Fetching remote code/text with javascript?

So I'm working on making a dynamic drop down select form and I need for each menu to propagate possible choices from a prebuilt chunk of html (located at, say, http://example.com/menu/choices) is there an easy way to use javascript to fetch the html of a remote page and then plug that in to the page? I know I can use .write() to insert the code, I just don't know how to fetch it.
Thanks!
Actually, you can't use write to insert the code, not once the initial page rendering is complete.
Loading Code
My first read of your question was that you wanted to load code — e.g., JavaScript. Here's how you do that, but see below.
The easiest way to do this is if your code exists at its source location in a JavaScript file all ready for inclusion in a file in the normal way. In that case, all you need to do is create a script element and add it to the document:
var script = document.createElement('script');
script.type = "text/javascript";
script.src = /* ... the URL of the code ... */;
document.body.appendChild(script);
document.body.removeChild(script);
Note that last line, removing the script node immediately after inserting it in the document. Inserting the node is all you need to do, that immediately triggers the process by which the JavaScript file is fetched and interpreted. You can remove the script element immediately (or not, it's up to you).
In the above, I've added the element to document.body because it's convenient and it doesn't matter where you add it. However, most scripts you see doing this will usually add it to the head instead. That's fine too. More in this article, although it's focussed on the Prototype library.
Speaking of libraries, all of the above notwithstanding, if you use a JavaScript library like jQuery, Closure, Prototype, YUI, or any of several others, it will probably make this (even) easier for you.
Update: Did you add the jQuery tag later? I didn't see it originally. With jQuery, if you're loading the script from the same origin as the document, you can use the getScript function:
jQuery.getScript('ajax/test.js');
// Or $.getScript('ajax/test.js');
However, getScript is not the same as the technique above. getScript will be hampered by the Same Origin Policy, whereas adding a script tag is not.
Loading Markup
If you want to load HTML markup and apply it to part of a page, that's easily done with jQuery.load:
$('#someid').load("yoururl.here");
That will replace the contents of the element with the id "someid" with the HTML returned from the given URL. Here's a live example that loads options into a select and another that loads text (a paragraph) into a div. This is easier with a library (like jQuery) because there are some issues around certain elements that libraries usually handle for you.
The thing you want is called AJAX (Asynchronous JavaScript and XML). If you're using jQuery:
$('#my-select-thingy').load('select-options.cgi');
or whatever flavour of server-side you prefer. You should have something like this in HTML:
<div id="my-select-thingy">
<!-- select will go here -->
</div>
and the url above should return something like this:
<select>
<option>Foo</option>
<option>Bar</option>
</select>
You're way better of using jQuery for that. Just look into the Ajax methods and you'll get the hang of it. http://api.jquery.com/category/ajax/
Suppose you have the following HTML markup
<div id="fakeDiv"></div>
you can execute an ajax request like this
$.ajax({
type: "get",
dataType: "html",
url: "http://example.com/menu/choices",
data: {},
success: function(response) {
$("#fakeDiv").html('').html(response);
},
});
to inject the html code returned by your url inside the DIV element.
This is jQuery code. Hope it helps!
Javascript usually can't access other websites for security reasons. If we could load content from wherever we wanted with a script we'd see some pretty rampant chaos. A simple solution is an iframe with the other document or just a section of it.
Does the website have anyway for you to access that info? If you can find an interface you can just get the info and stick in in the document. Otherwise you'd have to do some scraping.

Inline jQuery script not working within AJAX call

I have a issue:
while i call a inline script (wich uses jQuery too) from another page with ajax - it seems, that jQuery is no more defined (?), and I cannot use any of jQuery functions, that should be applied (according to inline script) to content.
It's basically a news list, which holds links to particular news items. I prefer using inline-script at this time, because I won't need this functionality elsewhere.
$.ajax({
url: href,
cache: false,
success: function(html){
$('#fancy_ajax').append($(html).find('.mainContentPadded'));
}
});
As you can see, I'm simply calling a part of another page and appending its contents to page.
When I load full page (not the part of it) - jQuery works as expected (that's why I came across the idea, that it needs to be "rebinded").
Thank you!
So if I understand your question correctly you have some JavaScript contained within the html variable ? If so it will not work, because JavaScript that is retrieved from an AJAX hit is not executed by the browser due to security risks.
I recommend you include the necessary javascript code in your page that is initiating the the Ajax request so that it is already available when you append the new content.
*edit...
monksp added a great link as a comment that shows how to have jQuery do exactly what you want.
Here's also some code to do the same but manually:
<html>
<head>
<title>Test JavaScript JSON</title>
</head>
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('jquery', '1.3.2');
</script>
<body>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON('testjs.json', function(json){
$(document.body).append(json.html);
eval(json.js);
});
});
</script>
</body>
</html>
Here's the content of testjs.json:
{"html":"<p class=\"newelement\">Click me</p>","js":"$(\".newelement\").click(function() { alert($(this).text()); });"}
And finally there are a bunch of existings plugins and other things to include javascript dynamically. I used YUI Get in the past: http://developer.yahoo.com/yui/3/get/
I'm confused by the question, I think. The bit of javascript that you have posted, is that loaded into the page via ajax? Like, you load the page in a browser, then something happens and that javascript gets loaded into the page? That won't work, because any javascript that gets loaded that way won't get executed.
I'd recommend loading it in the originating page's javascript if possible. If not, you could take the results of the ajax request, and walk through it looking for script tags, and eval() their contents as part of your success function. It's not really efficient (or super safe, make sure you absolutely trust where the loaded contents is coming from), but it'll get the job done.

Categories

Resources