Fetching remote code/text with javascript? - 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.

Related

How do I change and run js and css (less) files with ajax (using jquery)

When I click a botton I make an ajax call which loads different html code inside a div with the id 'main'. I have no problems getting the html code to show, but I can't find a way to change/add/include css and js code to my current page.
Or actually, I have found many different ways but non does what I want it to do.
First I tried to send over the link and script tags as strings inside a json object (with my other html code) and inserted them where I wanted them to be.
$('#main').children().remove();
$('#main').append(data.html);
$('body').append(data.js);
$('head').append(data.css);
it seems like this inserts them correctly when I 'inspect elements' and look under the 'sources' tab in the browser (chrome), but they don't execute/run.
Then, I tried to add id attributes to my css and js elements and then change the href and src attributes respectively (I have tried doing this both before and after my ajax call but both inside the click event). This allowed me to take away the css and js which belonged to the previous html code that was inserted in the div which is what I want.
$('#lessAjax').attr('href', 'location/style.less');
$('#jsAjax').attr('src','location/main.js');
and they are also included when I 'inspect elements' and look under the 'sources' tab in the browser (chrome), but obviously they don't execute/run either since this is pretty much the same thing as I did in the first example (only that now the code which is not used in my new view is taken away).
I then thought I had found a solution to the js file after finding the $.getScript() method since it executed my script which is directly under $(document).ready(function(){....}, but I noticed that the file cannot be found anywhere when I 'inspect elements' or when look under the 'sources' tab in the browser (chrome) so there is no way to take away or debug the code.
I have also tried
$('<link href="location/style.less" type="text/css" rel="stylesheet/less">')
.appendTo("head");
which includes the file but doesn't execute/run/work either.
I don't want to just include css and js code within script and style tags. I want to be able to switch css and js files as I change html code inside this div with Ajax (jQuery).
I have tried many more things in the 5 hours I spent trying to do this but I can't remember them all now. Surely this must be a common thing to do? Or are there any reasons for why I really shouldn't do this?
Any help would be much appreciated.
jqueryMobile: How to load external Javascripts
Can I load external stylesheets on request?
However please consider using a templating engine for content like this. There are many out there like underscoreJS and even frameworks that support them like Knockout, AngularJS and Backbone.
$("#somebutton").click(function(){
var path = 'path to css';
$.ajax({
url: path,
type:'HEAD',
error: function()
{
alert("failure")
},
success: function(result)
{
alert("success")
}
});
})

Load pages via AJAX and execute javascript and CSS

I've been searching for a while now, but I can't figure out how to load an entire page via AJAX and still execute all javascript and css.
Mostly I just end up with the plain text without any CSS.
Is there a way to do this? I tried jQuery.get, jQuery.load and jQuery.ajax, but none really work like that.
I have a different solution. You may try it with an iframe. Use jQuery to append an iframe script including all relevant codes into some part of your page (like some div). This may do it for you including CSS, like;
$('<iframe src="your_page.html"/>').appendTo('#your_div');
Or you may try something like;
$('<iframe src="your_page.html"/>').load(function(){
alert('the iframe is done loading');
}).appendTo('#your_div');
I have solved similar problem as following.
Download the webpage over ajax
Iterate it over and find any <script> and </script> tags
Get content from within these tags as text
Create new <script> element and insert there the code
Append the tag to your webpage
Another thing is you will need to somehow call the script..
I have done it this way:
I set standardized function names like initAddedScript callback which I am calling after appending the script to the page. Same as I have deinitScript called when I do not need the code (and its variables,..) anymore.
I must say this is awful solution, which likely means you have bad application architecture so as I have had:)
With css is it the same, but you do not need any handlers. Just append the style tag to your documents head.
If the page you load doesn't have any style data, then the external stylesheets must have relative paths that are not correct relative to the invoking document. Remember, this isn't an iFrame - you aren't framing an external document in your document, you're combining one document into another.
Another problem is that loading your complete page will also load the doctype, html, head, and body tags - which modern browsers will cope with most of the time, but the results are undefined because it's not valid HTML to jam one document into another wholesale. And this brings me to the third reason why it won't work: CSS links outside of the head section aren't valid, and the misplaced head section caused by your haphazard document-in-document collage.
What I'd do for compliance (and correct rendering) is this, which would be implemented in the Success callback:
Copy all link elements to a new jQuery element.
Copy the contents of all script in the head section
Copy the .html() contents from the loaded document's body tag
Append the link elements (copied out in step 1) to your host document's head
Create a new script tag with your copied script contents and stick it in the head too
Done!
Complicated? Kind of, I guess, but if you really want to load an entire page using AJAX it's your only option. It's also going to cause problems with the page's JavaScript no matter what you do, particularly code that's supposed to run during the initial load. There's nothing you can do about this. If it's a problem, you need to either rewrite the source page to be more load-friendly or you could figure out how to make an iFrame suit your needs.
It's also worth considering whether it'd work to just load your external CSS in the host document in the first place.
I suppose you are looking for something like this:
your page div --> load --> www.some-site.com
After a quik search the closest solution seems to be the one by "And": Load website into DIV
You have to run a web server and create a proxy.php page with this content:
Then your JQuery load() function should be like this:
$("#your_div_id").load("proxy.php?url=http://some-site.com");
NB. I have tested this solution and it should not load all the CSS from the target page, probably you'll have to recreate them. For example the image files stored on the remote server will not loaded, I suppose due to authentication policy.
You will be also able to view only the target page without the possibility to browse the target site.
Anyway I hope this could be a step forward to your solution.
Get your entire webpage as text using ajax
document.open();
document.write(this.responseText);
document.close();
OR
document.documentElement.outerHTML = this.responseText;
But you need to change the path of css and js pages in original webpage if the resulting webpage is in another directory.

How to update the html content of a single div?

I'm sure that this is a very simple problem, but I have multiple pages each with their own 'content' with page navigation at the bottom. Before I start coding a script to generate several different html files who all have head, body, and navigation footer code... how could I have only one instance of the navigation footer and have the links only update the content inside the 'content' div?
Very basic example of updating an element's content via JavaScript:
<div id="content"></div>
<script>
document.getElementById('content').innerHTML='<b>oh hai</b>';
</script>​​​​​​​​​​​​​
To do it when someone clicks on a link, you'd attach a function to the onclick handler for that link that does the updating and then returns false so the link won't do it's usual navigation.
If you don't want to have all the content loaded into a single file, you can use AJAX to retrieve content dynamically. You may wish to use a library/framework like jQuery to simplify the coding of AJAX interactions.
You can do this with AJAX. An example with jQuery is using the load function:
http://api.jquery.com/load/
This will fetch a given URL and load its contents into an element matched by a selector.
This can be solved in a few different ways. You'll either need to load all possible contents at once (easy to access content after load, but slow initial load), or you can asynchronously request content as your user requires it.
1) Hardcode all content into one page
By doing this, you'd have a selection of content blocks hidden on your page:
<div class="content-blocks">
<div class="content" id="content1">...</div>
<div class="content" id="content2">...</div>
...
</div>
Then, each link would have an event handler to load the appropriate content into your main content element.
document.getElementById('content1-link').onclick = function() {
document.getElementById('content-box').innerHTML = document.getElementById('content1').innerHTML
}
2) Make AJAX requests for content
To do this, your various content blocks would be stored in external files, e.g. 'content1.html', 'content2.html', etc. I would highly recommend using a javascript library with AJAX support for this method, as they will handle differences in how browsers handle asynchronous requests. Some, like jQuery, also provide convenience functions to do such tasks:
$('#content1-link').on('click',function(){
$('#content-box').load('/path/to/content1.html');
});
3) Use include statements
This method has the ease of implementation of the first solution (doesn't rely on async requests), but it keeps your content in separate files, like the second solution. Basically, you utilize whatever type of include your server/language supports (e.g. SSI includes, PHP require, etc). You would then create the event handlers as in the first option.

Why call $.getScript instead of using the <script> tag directly?

I don't understand the reason for replacing this:
<script src="js/example.js"></script>
with this:
$.getScript('js/example.js', function() {
alert('Load was performed.');
});
Is there a particular reason to use the jQuery version?
The only reason I can think of is that you get the callback when the script is loaded. But you can get that callback using a script tag, too, by using the load event (or on really old IE, onreadystatechange).
In contrast, there are several negatives to doing it this way, not least that getScript is subject to the Same Origin Policy, whereas a script tag is not.
Even if you need to load a script dynamically (and there are several reasons you might need to do that), frankly unless you really need the callback, I'd say you're better off just loading the script by adding a script tag:
$('head:first').append("<script type='text/javascript' src='js/examplejs'><\/script>");
(Note: You need the otherwise-unnecessary \ in the ending tag in the above to avoid prematurely ending the script tag this code exists within, if it's in an inline script tag.)
script tags added in this way are not subject to the Same Origin Policy. If you want the load callback, then:
$("<script type='text/javascript' src='js/examplejs'><\/script>")
.on("load", function() {
// loaded
})
.appendTo('head:first');
(As I said, for really old IE, you'd have to do more than that, but you shouldn't need to deal with them these days.)
I can think of three reasons you might use the jQuery form:
You want all of your script declarations at the top of your document, but you also know that placing script declarations there forces the browser to download them in their entirety before proceeding further in the page rendering process. This can introduce measurable delay. The jQuery form will schedule the script loads until after the document is finished downloading, similar to the effect of placing all of your <script> tags at the end of the document, only without the syntactic weirdness.
The <script> mechanism is not available to scripts that do not live in the HTML document itself; that is, if a script included on the page with <script> wants to load a script, it has no option but to use a JavaScript-based approach, such as calling the jQuery function.
The jQuery form allows notification of the script's successful execution, in the form of a supplied callback function.
No need to do that..
You do that if you want to load the script dynamically (when needed, and not from the beginning)
The script might depend on jQuery, so it would be a way to prevent the browser trying to load it if it hasn't loaded jQuery.
There are a number of reasons that jQuery might not load, from a simple network failure to a CDN not being whitelisted by a NoScript user.
maybe to control when a script is loaded? On a javascript heavy page, it may be worth waiting to load some things that are non essential until after essential things are loaded.

Programmatically remove <script src="/unwanted.js".. /> reference

I have partial control of a web page where by I can enter snippets of code at various places, but I cannot remove any preexisting code.
There is a script reference midway through the page
<script src="/unwanted.js" type="text/javascript"></script>
but I do not want the script to load. I cannot access the unwanted.js file. Is there anyway I can use javascript executing above this refernce to cause the unwanted.js file not to load?
Edit: To answer the comments asking what and why:
I'm setting up a Stack Exchange site and the WMD* js file loads halfway down the page. SE will allow you to insert HTML in various parts of the page - so you can have your custom header and footer etc. I want to override the standard WMD code with my own version of it.
I can get around the problem by just loading javascript after the original WMD script loads and replacing the functions with my own - but it would be nice not to have such a large chunk of JS load needlessly.
*WMD = the mark down editor used here at SO, and on the SE sites.
In short, you can't. Even if there is a hack, it would heavily depend on the way browsers parse the HTML and load the scripts and hence wouldn't be compatible with all browsers.
Please tell us exactly what you can and cannot do, and (preferably; this sounds fascinating) why.
If you can, try inserting <!-- before the script include and --> afterwards to comment it out.
Alternatively, look through the script file and see if there's any way that you could break it or nullify its effects. (this would depend entirely on the script itself; if you want more specific advice, please post more details, or preferably, the script itself.
Could you start an HTML comment above it and end below it in another block?
What does the contents of unwanted.js look like?
You can remove a script from the DOM after it is called by using something simple such as:
s = document.getElementById ("my_script");
s.parentNode.removeChild(s);
This will stop all functions of the script but will not take it out of user's cache. However like you wanted it can't be used.
Basically you can't unless you have access to the page content before you render it.
If you can manipulate the HTML before you send it off to the browser, you can write a regular expression that will match the desired piece of code, and remove it.

Categories

Resources