Can jQuery replace text with JavaScript that is then executed - javascript

I have a page with headers, images, etc. I'd like to replace a "page" div with another file of HTML, JavaScript, etc using Ajax and execute JavaScript on that page after it is loaded. How do I do this and also handle < , ", and other tags in the file and pass the page some parameters?

Is the other "page" content owned by you? If so, you can have javascript methods on your main "container" page, then once you fire the method to pull the contents of the new "page" div, fire the corresponding javascript method you need, since any necessary DOM elements will have been added to the page at this time.
To do it the way you mentioned, you can follow the steps seen here to use the dynamic script pattern: Executing <script> inside <div> retrieved by AJAX
Basically, you host your javascript externally, then once the page has loaded, add the "src" tag to a script element and it will execute.
As for handling special characters, you can follow steps with jQuery's ajax call to inject HTML from the other page into your current one, such as here: How to get the html of a div on another page with jQuery ajax?
$.ajax({
url:'http://www.example.com/',
type:'GET',
success: function(data){
$('#ajaxcontent').html($(data).find('body').html());
}
});
(Instead of targeting a specific div on the external page, you would target the body or parent container div)

given an html page
<html>
...
<body>
<div class="page">
some html content...
</div>
</body>
</html>
you can replace the content of the div via the jQuery function load()
$("div.page").load("an-http-resource.html");

Use an AJAX request to get the HTML file as a response.
Replace the "page" div innerHTML with the response.
If the HTML page has a bunch of headers and such and you only want a certain portion of that HTML file, you may want to use getElementById or some other method of selecting the portion of the HTML file.
The HTML entities will appear as they normally would in a browser, if that is what you mean by handling < and " and other tags.
You can send parameters by editing the endpoint:
index.html?date=today&car=yours

Related

Javascript change div content

My site has a one <div> for the header, one for navigation-panel and one for the content.
For the navigation-links i use
<p class="blue"><label onclick="goFor('test')"> -> TEST! <- </label> </p>
and my JS:
function goFor(destination)
{
document.getElementById("content").load(destination+'.php');
}
in this case, the content-div should change to the file "test.php".
but Firebug says: document.getElementById(...).load is not a function
what am i doing wrong?
Use $("#content").load(something) instead of document.getElementById.
Or... make an ajax request and load answer in that div.
For an ajax request with no lib, you can check my script here (first answer): Insert external page html into a page html. Note the success handle as you want it... with document.getElementById.

Static content in website

I've got a website and I'd like to make a part of it static. What happens is that the header, the menu bar and the footer are consistent in every page. I'd like to have them always loaded and when I click the menu button, it will only reload what is the body of the site.
Is there a simple chunck of code that can early achieve this? Something in js or ajax? I'm sorry but I don't have enough experience in these languages to accomplish something on my own. I've already tried to check jQuery library but it's still pretty confusing to me.
Thank you.
I think you don't even need Ajax or css!! Just use iFrames!! They are awesome, what happens is that u only design one page as the holder of your static content (Header-Menu ...) and put one iFrame in there as a place holder for any page you want to load in it, u should use proper css code to place the iFrame where you want, now, for every link in your menu, just set the "target" attribute equal to your iFrame's name and all the links will be loaded in that iFrame and your page won't be reloaded with every link click... I'll be back with some code...
Just add in every page a div container with ID for header, menubar and footer and just load it with this:
$(document).ready(function(){
$('#header').load('header.html');
$('#menubar').load('menubar.html');
$('#footer').load('footer.html');
});
Just make sure that the html files don't have html, head or body tags within, only the HTML-Code you would write inside the div. It's just like the include function in PHP.
EDIT:
For easy and simple implementation store the code above inside a .js file (e.g. include.js) and add this inside every head just below the include of all other scripts of your html files:
<script type="text/javascript" src="include.js"></script>
EDIT2:
Another solution ist to load the content of the page instead of the header, menubar, footer.
Here you take the same specifications (no html, body, etc. tags inside your content html files)
Name your content div e.g. <div id="content"></div>
Your navbar for example:
<div id="navbar">
Content1
Content2
</div>
JavaScript Code:
$(document).ready(function() {
//Click on a link that's child of the navbar
$('#navbar > a').click(function() {
//Get the html file (e.g. content1.html)
var file = $(this).attr('href');
//Load this file into the #content
$('#content').load(file);
return false;
});
});
You should consider the use of Server Side Included : http://httpd.apache.org/docs/current/howto/ssi.html
It's not quite easy to understand (as it refer to apache configuration), but this is a really great solution.
In a nutshell, you include parts of html code in you main page :
<!--#include virtual="/footer.html" -->
You won't have to use or understand all JQuery Framewol, user agent won't have to parse (if they are able to !) Javascript.
This is a pretty good replacement of PHP / ASP / Java for this kind of purpose.
You could use ajax to request the body of each page. But this is only one possibility - there are many. An other approach could be to create you page content using a script language (php, perl) serverside and employ a function there which adds footer, header and anything else to each page.
If you have an idea of Jquery then use click event on menu links to load the page in a div like the following syntax may help you.
$(document).ready(function(){
$("a.menu").click(function(){
$("#bodyContent").load("http://abc.com/your-linked-page.html");
});
});
To load the url dynamically use the following code:
In your menu bar the link looks like:
Home
In your Jquery code:
$(document).ready(function(){
$("a.menu").click(function(){
url = $(this).attr("title"); // here url is just a variable
$("#bodyContent").load(url);
});
});
Step 1: Add Jquery file into your html page.
Step 2: Use the above jquery code and change your menu link to the new what i said here.
Step 3: If you done it correctly, It will work for you.
How about a traditional iframe?
In your menu:
<a target="body" href="URL_to_your_Menu1_page">Menu1</a>
and then further in the document:
<iframe name="body" src="URL_to_homepage"></iframe>
You may use frameset and frames and organize you pages accordingly. So, frames containing menus can always be at display and while displaying contents on click of menu u may set target to frame in which you would like to load the contents.

Get variable and page fragment using Jquery .load() function

I am currently using Jquery's .load() function to insert a page fragment asynchronously. In the URL that I am loading the page fragment from, I also set a Javascript global variable value (in the script tag).
var loaded_variable = 'value1'
Is there a way I can use the .load() function to insert the page fragment AND retrieve the value of loaded_variable, something like the following code:
function loadProducts(url) {
$('#mainplace').load(url + ' #submain', function() {
current_variable = loaded_variable;
});
}
I am aware that script blocks are used when a selector expression is appended to the URL, so if the .load() function won't work, I'm open to other Jquery functions that can accomplish this.
Extra Info: The URL that I am loading from is written in HTML and Python (Web2py); the same Python variables are used to render the page fragment and set the loaded_variable value.
If you want to both fetch a fragment from a page and execute a script on it, you'll need a different approach. This is a bit hacky, but works.
$.ajax({url: 'fetch_page.html', dataType: 'text'}).done(function(html) {
var dom = $('<html />').prop('innerHTML', html);
$('body').append(dom.find('body p'));
$('head').append(dom.find('script'));
});
That fetches a p tag from our fetched pages and inserts it into the body of the parent page. It also executes any scripts in the fetched page.
If you're wondering about the prop('innerHTML... bit, that's because if I'd used jQuery's .html() method, it sanitises the input string and so we don't get the result we want.
My first thought was a document fragment, but you can't insert an HTML string into a doc frag - you have to append via DOM methods. Even then in this case it wouldn't really offer any saving over simply using an element to parse the dom (dom) as I have.
Bit hacky, as I say, but works.
I think I have a similar question. I have create a page that will hold a newsletter sign up. I want to load this page at the bottom of every blog post on my site. I don't want it in the footer because it is specific to my blog page and I want the ability to edit it without having to edit every blog post.
I created this page with the url /blog-newsletter-form which includes some code from an Email CRM.
I then added a div with a "blog-newsletter-form" class at the end of my blog posts and put the following in the page header to load the content from the first page section inside my blog posts.
$( document ).ready(function() {
$('.blog-newsletter-form').load("/blog-newsletter-signup #page .page-section:nth-of-type(1) .content");
});
This worked great except.. the load function is stripping the script from the newsletter page which is required for my newsletter form to work.
How do I load a page fragment but also keep the script for the newsletter. I tried using your sample code above and couldn't get it to work.

Using JQuery with a string (instead of DOM)

I remember using a plugin in the past where I could use AJax to load a page and update only part of the DOM. The AJax request returns the entire HTML page, but only a small portion of it replaces part of the currently loaded DOM.
For example, SO can use this function to fetch http://stackoverflow.com and only update #content. SO would make an AJax request to fetch http://stackoverflow.com, fetch #content from the returned string, and update #content of the DOM.
Sorry if my question is confusing. How would I do this without a plugin?
The .load() function is designed to do this. Just include a selector for an element along with the URL, like so:
$('#content').load('http://stackoverflow.com #content', optionalCallbackFunction);
That will replace the content of the element with ID content on the current page, with the contents of the element with ID content on the page returned by an AJAX request to http://stackoverflow.com, then run the function called optionalCallbackFunction. Assuming, of course, that the request was successful.
Without the AJAX, you can parse a raw string like this:
var str = "<div><h1>Page Title</h1><div id='content'>This is new.</div></div>";
var text = $("#content",$(str)).html();
$('#content').html(text);

How to append the HTML results of a URL call to the DOM?

I have a URL that resides on another domain, like this:
http://ads.adserver.com/ad?site=1233&zone=45435
When you type this URL in the browser, the result is HTML like this:
<img src="htt://ads.adserver.com/i/image.gif" border="0"/><br/>Test
The above renders as an image wrapped in a link with a second link below it.
I tried to capture this URL in a script tag and append it to the DOM, but it does not render the HTML above.
var ad_script = document.createElement('script');
ad_script.type = 'text/javascript';
ad_script.src = 'http://ads.adserver.com/ad?site=1233&zone=45435';
li.appendChild(ad_script);
Are there any other ways of invoking this URL and putting the result on the page? I can't use $.getScript() since I'm not invoking this in the global context. I need this HTML to appear exactly where I want it to appear.
EDIT: The only reason I am trying this route is that the third-party does not provide a JSON-P interface.
EDIT2: Unfortunately, I am not on an application server.
EDIT3: This is for iPhone.
You are limited to how you load this due to cross-domain issues .. an easy way would be to load the image in it's own iframe
<iframe src='http://ads.adserver.com/ad?site=1233&zone=45435' height='200px' width='200px' />
You'll want to use ajax for this. The easiest way might be jQuery's .load() method.
Assuming the element you want the content to go into has an id of holder, you would do
('#holder').load('http://ads.adserver.com/ad?site=1233&zone=45435')
It will put the contents of the webpage into your selected element. http://api.jquery.com/load/
edit: Sorry, forgot cross-site ajax limitations. You could instead set up a php page like:
if(isset($_GET['url'])){
echo file_get_contents($_GET['url'])
}
and then do
('#holder').load('http://yoursite.com/yourpage.php?url=http://ads.adserver.com/ad?site=1233&zone=45435')
Take the jsonp approach. use an actual script tag and put an executing javascript function as the response that adds that html markup to the dom. It will add it to the dom of the page where the script tag resides.
There are a number of jQuery ajax calls that can accomplish this, for example:
jQuery.get('http://ads.adserver.com/ad?site=1233&zone=45435', function(data){jQuery(updateElementQuery).html(data);});
Try to use jquery method 'load'
`$('#result').load(url, function(response) {
$('#my-li').append($('#result').html());
$('#result').html(null);
});`
... where #result is some hidden div

Categories