Load HTML page dynamically into div with jQuery - javascript

I'm trying to make it so when I click on a link in a HTML page, it dynamically loads the requested page into a div with jQuery.
How can I do that?
<html>
<head>
<script type="text/javascript">
// what can I do for load any url clicked?
</script>
</head>
<body>
<div id="content"></div>
Page 1<br />
Page 2<br />
Page 3<br />
Page 4<br />
Page 5<br />
Page 6<br />
</body>
</html>

There's a jQuery plugin out there called pjax it states: "It's ajax with real permalinks, page titles, and a working back button that fully degrades."
The plugin uses HTML5 pushState and AJAX to dynamically change pages without a full load. If pushState isn't supported, PJAX performs a full page load, ensuring backwards compatibility.
What pjax does is that it listens on specified page elements such as <a>. Then when the element is invoked, the target page is fetched with either the X-PJAX header, or a specified fragment.
Example:
<script type="text/javascript">
$(document).pjax('a', '#pjax-container');
</script>
Putting this code in the page header will listen on all links in the document and set the element that you are both fetching from the new page and replacing on the current page.
(meaning you want to replace #pjax-container on the current page with #pjax-container from the remote page)
When <a> is invoked, it will fetch the link with the request header X-PJAX and will look for the contents of #pjax-container in the result. If the result is #pjax-container, the container on the current page will be replaced with the new result.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.pjax.js"></script>
<script type="text/javascript">
$(document).pjax('a', '#pjax-container');
</script>
</head>
<body>
<h1>My Site</h1>
<div class="container" id="pjax-container">
Go to next page.
</div>
</body>
</html>
If #pjax-container is not the first element found in the response, PJAX will not recognize the content and perform a full page load on the requested link. To fix this, the server backend code would need to be set to only send #pjax-container.
Example server side code of page2:
//if header X-PJAX == true in request headers, send
<div class="container" id="pjax-container">
Go to next page.
</div>
//else send full page
If you can't change server-side code, then the fragment option is an alternative.
$(document).pjax('a', '#pjax-container', {
fragment: '#pjax-container'
});
Note that fragment is an older pjax option and appears to fetch the child element of requested element.

JQuery load works, but it will strip out javascript and other elements from the source page. This makes sense because you might not want to introduce bad script on your page. I think this is a limitation and since you are doing a whole page and not just a div on the source page, you might not want to use it. (I am not sure about css, but I think it would also get stripped)
In this example, if you put a tag around the body of your source page, it will grab anything in between the tags and won't strip anything out. I wrap my source page with and .
This solution will grab everything between the above delimiters. I feel it is a much more robust solution than a simple load.
var content = $('.contentDiv');
content.load(urlAddress, function (response, status, xhr) {
var fullPageTextAsString = response;
var pageTextBetweenDelimiters = fullPageTextAsString.substring(fullPageTextAsString.indexOf("<jqueryloadmarkerstart />"), fullPageTextAsString.indexOf("<jqueryloadmarkerend />"));
content.html(pageTextBetweenDelimiters);
});

Try with this one:
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
$("#content").load($(this).attr('href'));
});
});
and make sure to call this library first:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>

I think this would do it:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".divlink").click(function(){
$("#content").attr("src" , $(this).attr("ref"));
});
});
</script>
</head>
<body>
<iframe id="content"></iframe>
<a href="#" ref="page1.html" class="divlink" >Page 1</a><br />
<a href="#" ref="page2.html" class="divlink" >Page 2</a><br />
<a href="#" ref="page3.html" class="divlink" >Page 3</a><br />
<a href="#" ref="page4.html" class="divlink" >Page 4</a><br />
<a href="#" ref="page5.html" class="divlink" >Page 5</a><br />
<a href="#" ref="page6.html" class="divlink" >Page 6</a><br />
</body>
</html>
By the way if you can avoid Jquery, you can just use the target attribute of <a> element:
<html>
<body>
<iframe id="content" name="content"></iframe>
<a href="page1.html" target="content" >Page 1</a><br />
<a href="page2.html" target="content" >Page 2</a><br />
<a href="page3.html" target="content" >Page 3</a><br />
<a href="page4.html" target="content" >Page 4</a><br />
<a href="page5.html" target="content" >Page 5</a><br />
<a href="page6.html" target="content" >Page 6</a><br />
</body>
</html>

I think you are looking for the Jquery Load function. You would just use that function with an onclick function tied to the a tag or a button if you like.

You can use jQuery's getJSON() or Load(); with the latter, you can reference an existing html file. For more details, see http://www.codeproject.com/Articles/661782/Three-Ways-to-Dynamically-Load-HTML-Content-into-a

You can through option
Try this with some modifications
<div trbidi="on">
<script type="text/javascript">
function MostrarVideo(idYouTube)
{
var contenedor = document.getElementById('divInnerVideo');
if(idYouTube == '')
{contenedor.innerHTML = '';
} else{
var url = idYouTube;
contenedor.innerHTML = '<iframe width="560" height="315" src="https://www.youtube.com/embed/'+ url +'" frameborder="0" allowfullscreen></iframe>';
}
}
</script>
<select onchange="MostrarVideo(this.value);">
<option selected disabled>please selected </option>
<option value="qycqF1CWcXg">test1</option>
<option value="hniPHaBgvWk">test2</option>
<option value="bOQA33VNo7w">test3</option>
</select>
<div id="divInnerVideo">
</div>
If you want to put a default page placed inside id="divInnerVideo"
example:
<div id="divInnerVideo">
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/pES8SezkV8w?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>

Related

LIghtBox2 data-title description link with JavaScript

the latest version of LightBox2 (v2.8.2) now allows a link to appear in the text under an image. This works fine usually. But my link needs to call some javascript code.
The code below for example works fine when you click on Click Here.
<a class="example-image-link"
href="http://lokeshdhakar.com/projects/lightbox2/images/image-3.jpg"
data-title="<a href='http://localhost/'>Click Here</a> ">
<img class="example-image" src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-3.jpg" alt=""/>
</a>
For my code, I need the href within data-title to call some javascript code. These are the ones I've tried.
data-title=" <a href='javascript:submitFormFunction();' >caption </a> ">
data-title=" <a href='#' onclick='submitFormFunction();' >caption </a> ">
data-title=" <a href='#' class='submitCreateFromPreview' >caption </a> ">
None of these work, the javascript code never gets called. It appears that if the href is not a normally structured URL (http://www.google.com or http://localhost) it simply does nothing.
This is my javascript code
$(".submitCreateFromPreview").click(function(){
submitFormFunction();
});
function submitFormFunction() {
form=document.getElementById('mainform_id');
form.target='_self';
form.action='http://localhost/create.do';
form.submit();
}
I basically need all the fields in my form to be submitted when they click on the href. This code works in other places in my webapp but it does not want to work with the LightBox description href.
Any ideas what I'm doing wrong? Or anyone else have other options that perhaps I haven't tried?
Any help would be appreciated.
Thanks
We can use jQuery '.on()' event handlers for adding events. These have the advantage that they can process events from descendant elements that are added to the document at a later time.
In above case we can have the code like below:
$(document).ready(function(){
$(".lightbox").on("click",'.submitCreateFromPreview', function (e) {
submitFormFunction();
});
});
Even if the function is accessed directly, it executes. So, either of the two options can be implemented to execute "submitFormFunction()" function.
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Lightbox Example</title>
<link rel="stylesheet" href="../dist/css/lightbox.min.css">
</head>
<body>
<section>
<h3>Two Individual Images</h3>
<div>
<a class="example-image-link" href="http://lokeshdhakar.com/projects/lightbox2/images/image-1.jpg" data-lightbox="example-1" data-title="Optional <img class="example-image" src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-1.jpg" alt="image-1" />
<a class="example-image-link" href="http://lokeshdhakar.com/projects/lightbox2/images/image-2.jpg" data-lightbox="example-2" data-title="Optional <img class="example-image" src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-2.jpg" alt="image-1"/>
</div>
</section>
<script src="../dist/js/lightbox-plus-jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
function submitFormFunction(){
alert("Submit Form Function executed :: ")
console.log("Submit Form Function executed :: ");
}
$(document).ready(function(){
$(".lightbox").on("click",'.submitCreateFromPreview', function (e) {
submitFormFunction();
});
});
</script>
</body>
</html>
Functional repository using LightBox2 (v2.8.2) can be accessed here
https://github.com/nitinsinha/Debugs.git

Using PHP to replace only (current) <div> content from <form> submit button

I have a single 'index' page that replaces the 'mainContents' when any button in the navBar is pressed.
This is so that I can re-load only the contents needed, and keep the header, navbar, and footer static.
This is causing me trouble in my "search.html" page (which is loaded into the #mainContents ).
search.html has a form which (will) call some sql queries via PHP. When I initially designed this webpage I had it spanning across multiple pages; re-loading header, footer, etc each time. So I just re-loaded the whole page with the new 'php' contents (which will be a table populated with data).
Now that 'search.html' is located inside the #mainContents of the 'index.html' page, when the 'go/submit' button is pressed, the entire page is reloaded, and I lose my header and footer...
I've been at this for a while now, and I am at a loss as to how to make it work.
I'll include relevant pages/scripts (though it seems like a bit much, I'd rather you have the information available)
Index.html (main page):
<!DOCTYPE html>
<head>
<title>NoteVote</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<link rel="stylesheet" href="./NV_home.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
</head>
<body>
<div data-role="page" id="noteVote">
<!-- HEADER -->
<div data-role="header" align="middle" class="header">
<img src="images/banner_post_it.png" align="middle" alt="Banner Image" height="100" width="250"/>
<!-- NAVBAR -->
<div data-role="navbar" data-grid="c" id="navBar">
<ul>
<li><a class="ui-btn" id="coursesButton">Courses</a></li>
<li><a class="ui-btn" id="searchButton">Search</a></li>
<li><a class="ui-btn" id="submitButton">Submit</a></li>
<li><a class="ui-btn" id="accountButton">Account</a></li>
</ul>
</div>
<!-- /NAVBAR -->
</div>
<!-- /HEADER -->
<!--
This is the MAIN section.
This is where the contents will be replaced
-->
<div data-role="content" class="ui-content" id="mainContent">
Site-related text.
</div>
<!-- /MAIN -->
<!-- FOOTER -->
<div data-role="footer" class="footer">
This is the footer.
</div>
<!-- /FOOTER -->
</div>
<!-- /INDEX -->
<script src="./scripts/navScript.js"></script>
</body>
</html>
navScript.js is the script that causes the nav-buttons to replace only the #mainContents :
$(document).ready(function() {
// Actual script includes code for each nav-bar button.
$("#searchButton").on("click", function(e) {
e.preventDefault();
$("#mainContent").load("./pages/search.html");
});
Then the 'search.html' which only replaces the #mainContent .
(this is where it gets messy, as I've tried a few ways to get this to work how I want):
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="main" data-role="content" id="main">
<div id="holder">
<h1>Search</h1>
<div class="left">
<form id="searchForm">
<b>Course:</b>
<select name="course">
<option value="*">All</option>
<option value="COMM2216">COMM-2216</option>
<option value="COMP2121">COMP-2121</option>
<option value="COMP2510">COMP-2510</option>
<option value="COMP2526">COMP-2526</option>
<option value="COMP2714">COMP-2714</option>
<option value="COMP2721">COMP-2721</option>
</select>
<p>
Type:
<input type="radio" name="type" value="lec">Lecture
<input type="radio" name="type" value="lab">Lab
<input type="radio" name="type" value="*" checked>Both
<p>
<input type="submit" value="Go" id="searchGoButton">
</form>
</div>
</div>
</div>
<script src="./scripts/searchGo.js">
</script>
</body>
</html>
And finally 'searchGo.js', is the code that is supposed to enforce only the "search.html" page to change (inside the #mainContent ), so that the header, footer, etc stay present.
$(document).ready(function() {
$("#searchForm").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: "./scripts/php_test.php",
data: "blah",
success: function(){
$("#holder").load("../pages/account.html");
}
}) ;
} );
This is just a sample/test to see if it would work; but it reloads the whole page.
It is my intention that searchGo.js will load a .php script that will call the sql queries, and populate a table and replace the #mainContent div with its
Again, I apologize for all the code, and if my problem is vague... I'm totally stumped, and would greatly appreciate any help. My alternative is to go back to reloading the navbar and header with each page; which I will resort to soon if no one can offer assistance.
Any suggestions of alternate means to accomplish this task are more than welcomed.
Try to add onsubmit="return false;" on the search form tag. The problem is that you don't override default submit button form behavior. That is the reason that your form submitting is refreshing the whole page.
Something like this:
<form onsubmit="return false;">
<input id="submitButton" type="submit" />
</form>
You can call your search function like this
$(document).ready(function() {
$('#submitButton').on('click', function() {
console.log('Form submitted');
console.log('Ajax call');
console.log('Insert returned data');
});
});
Js bin link
You need to delegate the event for that button -
$("body").on("submit", "#searchForm", function(e)...
Because search.html is loaded into the DOM via AJAX jQuery is "unaware" of it. The submit bubbles up the chain though and can be "captured" at a level that was already there when jQuery initially ran. The submit bubbles up to the body then jQuery sees it and acts.

site-onload-gif within php

problem is, that the website is loading like for about 20 second or longer (user-problems preprogrammed)
my solution was to load a pre-site where the user sees a loading screen.
i did this with this html-site but i want to do the same in php.
the test-page is http://kater.selfhost.me/test/
Source Code:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script type="text/javascript">
window.onload = function() {
document.getElementById("siteLoader").style.display = "none";
document.getElementById("container").style.display = "block";
}
</script>
</head>
<body>
<div id="container" style="display:none">
<div id="body">
<iframe src="http://kater.selfhost.me/stats/skins.php" frameborder="0" height="2000px" width="1024px"></iframe>
</div>
</div>
<div id='siteLoader'>
<div id='siteDetailLoader'>
<img src='ajax_loader.gif' border='0'>
Please wait while the page loads...<br /> <br />
</div>
</div>
</body>
</html>
i tried some workarounds, but after searching & testing for about three hours i give up...
thanks in advance for any help provided! :-D
Adding what I alredy said at your question commentary, I made a code loading this content via AJAX:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
//Load content
loadAjaxContent();
});
function loadAjaxContent()
{
//VERY IMPORTANT: the URL domain MUST HAVE be the same as your request
//that's why I'm not writting the full http://kater.selfhost.me/stats/skins.php
$.ajax({
url: "/stats/skins.php"
}).done(function(data) {
//remove loader
$("#siteLoader").hide();
//put PHP content
$("#ajaxContent").html(data);
});
}
</script>
</head>
<body>
<div id="body">
<div id="ajaxContent" style="width:1024px;"></div>
<div id='siteLoader'>
<div id='siteDetailLoader'>
<img src='ajax_loader.gif' border='0' />
Please wait while the page loads...<br /> <br />
</div>
</div>
This is the most used way to load asynchronous content in the web. But pay attention at this: The http://kater.selfhost.me/stats/skins.php page is made to open as single page in the web, so it has <html> , <head>, <body> , etc.. tags, so..after loading this page into another you'll have two <html>, <body> .. tags in a same page, this is bad, but modern browsers have an awesome common sense and don't bother by this, but you should know that, and be aware.
The actual problem why it isn't loading yet, is this javascript in your content:
<script type="text/javascript"><!--
EXref="";top.document.referrer?EXref=top.document.referrer:EXref=document.referrer;//-->
</script>
I removed that and now works fine. Remember that's a quick fix, I don't know what this JS does.
Why it works in <iframe> and doesn't via AJAX? When you open in <iframe> is like opening in a new browser window..and via AJAX, as I have said, it'll load the page content straight inside your "parent" page.
So, removing this Javascript will work, but awesome further solutions:
If you need to open this page both as content to load (via AJAX), both as single page, you can make two pages.. one for each need.
If you just want to use as content to load, remove <html>, <head>, etc.. tags, and fix Javascript to work inside another page.

How do I get PrettyPhoto to work with a MVC3 Content Handler?

I am using PrettyPhoto 3.1.4 from http://www.no-margin-for-errors.com
I am using a content handler in ASP.NET MVC3 to load images from a database. Pretty Photo is not loading the images with the API. How do I get it to work with the content handler?
Here is an image that should popup a gallery of images:
<a href='' onclick="$.prettyPhoto.open(api_images0,api_titles0,api_descriptions0);" title='UFC123'>
<img style="max-height: 160px;max-width: 260px;" id='Img31' alt='UFC123' title='UFC123' src='/img.ashx?mediaId=31' style='padding:10px' />
</a>
Here is the script I am using:
<script type="text/javascript" charset="utf-8">
var api_images0 = ['/img.ashx?mediaId=33'];
var api_titles0 = ['Gina'];
var api_descriptions0 = ['Gina Description'];
</script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$("a[rel^='prettyPhoto']").prettyPhoto({ theme: 'dark_rounded', social_tools: '' });
});
</script>
The documentation isn't clear about the "public api" functions that you are trying to use, and there isn't a demo for those functions, but my guess is that because you don't have any a elements that have rel="prettyPhoto", the .prettyPhoto() function is never run, so the supporting HTML that shows the popup box is never added to the DOM. Try adding rel="prettyPhoto" to your a element and see if that helps.
There were no javascript errors. I figured it out. The problem was that I needed the pound sign instead of the empty string for the href tag.
<a href='#' onclick="$.prettyPhoto.open(api_images0,api_titles0,api_descriptions0);" title='UFC123'>
<img style="max-height: 160px;max-width: 260px;" id='Img31' alt='UFC123' title='UFC123' src='/img.ashx?mediaId=31' style='padding:10px' />
</a>

How to ignore base href when using location.href="#_ElementId_"?

If a webpage has a base href, is there anyway to ignore it when we're using #ElementId, without refreshing the page?
Here's some code:
<html>
<head>
<base href="http://www.google.com/" />
</head>
<body>
<div id="test">
Test
</div>
<button onclick="location.href='#test'">Back to Test</button>
Back to Test!
</body>
</html>
When I click on either the button or the link, I want the browser to bring the page to div#test. Without the base href tag, everything works - However, with the base-href tag, I can't do it without the help of Javascript. Is there a way to do it in a more "natural" way?
Below's a workaround that I have at the moment...
<html>
<head>
<base href="http://www.google.com/" />
<script type="text/javascript">
function goToElement(elementId) {
var baseTag = document.getElementsByTagName("base")[0];
var existingBaseHref = baseTag.href;
baseTag.href = "";
location.href = "#" + elementId;
baseTag.href = existingBaseHref;
}
</script>
</head>
<body>
<div id="test">
Test
</div>
<button onclick="goToElement('test')">Back to Test</button>
<a onclick="goToElement('test')">Back to Test!</a>
</body>
</html>
This will scroll to the element with id="test" and the return false will make it stay on the page.
Go to div with id=test
It does not seem to be possible to do what you want without either using script or addIng the full path to the href on the server
You might just have to output the full absolute URL in your link's href attribute.
For example, you could do something like this in ASP.NET (using the AntiXss library):
<a href="<%= AntiXss.HtmlAttributeEncode(Request.Url.AbsoluteUri) %>#test">
Link text...
</a>
Or something like this in PHP:
<a href="<?php echo htmlentities($_SERVER['REQUEST_URI'], ENT_QUOTES, 'ISO-8859-1'); ?>#test">
Link text...
</a>
I had a similar issue when using . This was my solution that worked on interior pages, for example www.mozilla.org/about
<div>
<p>Content...</p>
<div id="target">
Target Div
</div>
</div>

Categories

Resources