How to update the html content of a single div? - javascript

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.

Related

Display DB content to a DIV based on a link click [duplicate]

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.

cURL returns full HTML via AJAX - how to display to user?

I am building a Wordpress plugin to display a list of jobs to a user pulled from a recruiting platform API. On click of a job, a cURL request is sent to the API that pulls the job details as a full HTML page (the online job advertisement). I have everything working fine in terms of pulling the HTML, but I cannot figure out how to display it to the user.
How can I either:
Open a new tab to display the HTML pulled from the AJAX request
or
Open the full HTML within a div on the same page (i.e. a modal)
I would prefer to open the HTML in a new page, but don't know how to use jQuery to do this... Opening within the page in a modal is also fine, but as far as I understand iFrames (which I would rather not use anyway), you have to pass a url (and I simply have the full markup). Is there a way to display this within a page, perhaps using canvas? It carries its own links to CSS and Javascript that need to apply only within that sub-page.
EDIT:
As a clarification, I know that I can simply place the HTML within the page. My issue is that it is a full page. This means it has a <head> <body>, and its own CSS links. Just putting it in the page messes with the rest of the CSS and produces invalid HTML.
This is what I already have:
$.post(ajaxurl, data, function(response) {
$('.sg-jobad-full').html(response);
});
It places the response within the page perfectly well... but it messes up the page by introducing a <body> within a <body> and competing CSS.
If you put the response in a <div>, it will mess the markup because css/js/meta definitions may not be put into the <body>.
If there is a way to retrieve the data without the markup already beeing in, you could parse the data and let it print via a javascript, which is the method I'd prefere.
According to your comment, you should really go with iframes, all other methods will alter your markup to have <html> tags inside <html>, which is very bad practice.
Iframes can be styled just like a <div> element, and it is realy not dirty to use iframes for the purpose you mentioned (it does not load from a foreign host, it is not hidden, it does not track).
<iframe class="job-offers-plugin" src=".../wp-content/plugins/yourplugin/getJobs.php">
</iframe>
Put some style into it like width;height;padding;margin;overflow; place it where you like..
This helps you with the databse:
Using WPDB in standalone script?
Add permalinks to your plugin script:
http://teachingyou.net/wordpress/wordpress-how-to-create-custom-permalinks-to-use-in-your-plugins-the-easy-way/
If you get the full HTML in an jQuery.ajax(...) call, you can always just show it in a certain div on your page.
$.ajax({
success: function (resp){
// resp should be your html code
$("#div").html(resp);
}
});
You can use the $(selector).html(htmlCode) everywhere you want. You can insert it into modals, divs, new pages...
If you have to inject a whole HTML page you can:
strip the tags you don't need
or
use an iframe and write the content to that iframe: How to set HTML content into an iframe
iframes aren't my favourite thing... but it's a possibility

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.

Multiple pages on a single page

I am using backbone.js and building a single page application, inspired by trello.com ..
I want to know how you show many pages on top of the original page. As in how you architect it.
How do you use Backbone routers to achieve this?
For example in trello
Basepage
And then now on top of the base page you have dynamic content
like a cards detail
like a boards details
How could i architecture something like this?
I've done a couple of approaches so far in projects with 50+ pages and they both scaled well. I did not use backbone.js but the approaches are straight forward and do not require a framework to learn other than I used jQuery for selectors.
Both of them have in common creating a single overlay window that you can pull in content into the window. I wrote mine from scratch but you could easily use jQuery UI dialog. The two approaches only differ in how the content is pulled. Also, using the information on the link is all you should need to pull in the "module" or overlay content as your rule. Do not need tons of scripts loaded in to start your app. Have the modules pull in the behavior for you.
Option 1) Use the jQuery load method to pull content from stand-alone web pages by using a placeholder variable like so:
var $ph = $('<div />');
$ph.load(URL); // loads gui of remote URL + executes any script that URL has
The $ph var now contains all the GUI loaded in from the external URL so you can use selector on it to extract the particular HTML and place it into your DOM or overlay as you need.
Here is an example of the stand-alone HTML output:
<div class="module">
<a class="link">click me</a>
</div>
<script>
(function(){
// put any private vars here
$('.module .link').click(function(){
// do something
});
})();
</script>
If you remove() or destroy the dom inside the overlay through jQuery, it will automatically remove all the events directly assigned aka "bind" and "unbind" them but using "live" or "delegate" you will need to worry about "die" and "undelegate" etc. just doing die('.namespace').live('click.namespace') will ensure is cleaned.
Here is an example of this on one of my websites -> http://www.kitgui.com/docs
But the better example is within the customer section as the docs is fairly simple using hash history.
2) Using an iframe inside your overlay and assigning it a URL.
This is the easiest option but is a little slower because each page called has to have a full standalone behavior and dependencies with the iframe. Also you must worry about sizing the frame etc. unless you have a fixed overlay window.
You must have a loader overlay your iframe while its loading then have the iframe talk the parent to tell it its done loading and hide the loader.
I did this for several sites but one of them is a site in development you can see here to get the code ->
http://dev.zipstory.com (sign in and go to my zipstory and click "group" settings etc to see this, just view source to see how I did this as its all there)
The thing about iframes is you should write some code on the parent that accepts standard messages from the iframe that you agree on as a typical set of behavior such as notifying its done loading or passing messages to update something on the parent etc. This can be added on the fly and refactored as you need as long as your aim is KISS approach.
Each of the 'dynamic content' pages should be a template (underscore.js gives you _.template()) rendered by a backbone view. The main page needs to have events that initialize new views and render the templates. Look at the todos app (http://documentcloud.github.com/backbone/docs/todos.html) to get a basic idea about the flow of a backbone app.

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.

Categories

Resources