Including PHP depending on screen width size - javascript

I read a lot about it, I tried a lot as well... I almost think it's possible, but I need your help.
I want to load some content depending on the screen width. It's a sticky navbar with social network sharing buttons (follow on twitter, like on facebook, the usual).
Using this code, It loads the html, perfectly. BUT the scripts inside it, does not. I use jQuery animation to show the buttons when the cursor is over the logo, and the buttons use javascript to, well, work. But, loading this way, it's like there was no scripts inside that html.
$(function () {
var width = $(window).width();
if (document.documentElement.clientWidth >= 992)
$('#Navbar').load('navbar.html');
});
I tried with PHP, then. A simple include() worked. The navbar was loaded the way it was supposed to.
Since PHP cannot know the screen width (and since I am using bootstrap, I following it's screen sizes), I thought I could do this (I changed the .html to .php, it's all the same)
$('#NavBar').append('<?php include "navbar.php"; ?>');
But it doesn't work.
Is there a way for me, using jQuery, to call the include()? Or any other way that could make this work?
Media queries and display: hidden are not options. I don't want to load the content and keep it hidden. I want to just load it when it's needed.

These are two completely different programming languages so you can't call a php function from your javascript.
but you can call a reload of the page with some parameters or some kind of new url to make this work with php.
Example onepage php site:
<html>
<head>
<!--Your Stuff-->
</head>
<body>
<?php
//access the parameter and it's value with php's global $_GET
if(isset($_GET["mobile"]) && $_GET["mobile"] == 992){
include "navbar.php";
}
?>
<script>
//check if the document has the specified width and also if the parameter is already set
if (document.documentElement.clientWidth >= 992 && window.location.href.indexOf("?mobile=992") == -1) {
window.location.href = window.location.href + "?mobile=992";
}
</script>
</body>
</html>
The Example above works if you don't have any additional get parameters on the site and navbar.php only contains valid html stuff.

Related

why the data not loaded in the table when the page in the print dialog

i have a problem here
i make a page that have function for print page that contain of dynamic table. the print function method is open the page html that contain the dynamic table in the new tab then open the print dialog. the process going well but when i add the ajax call for displaying the data in the dynamic table. the data not displayed at the table in the print dialog..but when i cancel the print dialog and the page that must be printed show off the data is displaying there...
how to fix it.
this the picture of the page
i use this code for print that
<script>
function myFunction() {
window.open('SPL.html','','height=650,width=1200').print();
}
</script>
You didnt provided yet the code of your generator, so I simply explain you why its not working and what you can do.
A good reference for window Mozilla Window Open
You can read there more details about possible functions and more. Your problem is, with:
window.open('SPL.html','','height=650,width=1200').print();
Directly after opening the file you call the print function, at this moment your script and ajax request don´t have finished yet. Thats why it just shows you the current state with the predefined html and css code.
So what you have to do is simply call print after it has finished. There are tons of ways to achieve this.
The simplest way would it to open it like this:
window.open('SPL.html','','height=650,width=1200')
Inside your SPL.html you stack your js script inside:
$(document).ready() {
//Your Generator
}
This little piece keeps safe that all dependencys (external scripts and dom elements) are created before your generator runs and it gives us the possibility for the next function:
$(window).load(function(){
window.print()
});
This one is a version of the globalEventHandler window.onload. It basicly ,if you read the documentation, fires after everything is loaded, including images, frames, objects and so on. And the tricky part also after document.ready, this makes it sure that our generator is finished before we run the print command.
I hope this helps, If you really want to stick the print command inside your first page I can give you an example of this too. But it is not as bullet prove as this solution. Ah and if you want to stick with #Saurabh solution you have to use allow-modals for your Iframe, if not it wouldn´t be possible to print. Is also mentioned in the official documentation.
This issue is caused because the page is not completely loaded before calling the print function.
Update: Using jQuery
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function(){
$('#loaderFrame').load(function(){
var w = (this.contentWindow || this.contentDocument.defaultView);
w.print();
});
$('#loaderFrame').attr('src', 'SPL.html');
});
});
</script>
<style>
#loaderFrame{
visibility: hidden;
height: 1px;
width: 1px;
}
</style>
</head>
<body>
<iframe id="loaderFrame" ></iframe>
</body>
</html>

How to keep elements non-refreshed

The main goal is to keep non-refreshed the logotext <div class="small-7 medium-4 columns logo"> and the menu <nav class="pagedMenu" role="navigation">,without clipping on page refresh or while the content is loading from a page to another. Also, the menu state should be preserved from a page to another.
I've found here a possible solution that could solve the problem (you could use ajax to fetch the updated content and use jQuery to put the new content on the page and avoid the refresh entirely. Doing it that way, the existing data in the page would remain untouched. said #jfriend00)
So, I have tried to use an Ajax plugin (called AWS). In the AWS option page, I (suppose) that I've done the right thing pointing wrapper as Ajax container ID and also pagedMenu as Menu container class, Transition Effect Enabled, No ajax container IDs blank, no loader selected, having already a pulse loader implemented in the theme.
At this point, all I got it's a menu / side-menu (shiftnav) / pulse dot loader / content loading malfunction, generated perhaps by the wrong defined Ajax container id and/or menu container class(?) OR by a conflict with an existing JS / jQuery code, not so sure.
Also in Chrome console there is an error:
Uncaught SyntaxError: Unexpected token ;
(anonymous function) # ajaxify.js?ver=4.3.1:175
n.extend.each # jquery-2.1.4.min.js?ver=2.1.4:2
n.fn.n.each # jquery-2.1.4.min.js?ver=2.1.4:2
$.bind.$.ajax.success # ajaxify.js?ver=4.3.1:169
n.Callbacks.j # jquery-2.1.4.min.js?ver=2.1.4:2
n.Callbacks.k.fireWith # jquery-2.1.4.min.js?ver=2.1.4:2
x # jquery-2.1.4.min.js?ver=2.1.4:4
n.ajaxTransport.k.cors.a.crossDomain.send.b # jquery-2.1.4.min.js?ver=2.1.4:4
Everything is getting back to normal on page refresh but doesn't help at all, being useless.
I also have to mention that for the menu I've tried to keep the state using jQuery-Storage-API and storage=jQuery.sessionStorage; as you can see in mynewmenu.js file but that will not solve the non-refreshing elements problem.
The menu jsfiddle only, if this helps to have the whole picture, here thanks to #Diego Betto.
You can use this live link as example; there is a similar situation with the above described - Ajax implementation right(?) - and regarding the appearance, menu is kept non-refreshed from one page to another; if you browse Books, Works etc, menu sections you'll see; if there is a model that could be implemented here, I'll be glad to find it.
LE: meanwhile, I've tried another ajaxify solution made by #arvgta - special thanks - without success yet but as far as I've found from the Author, the defined elements should be div's with id's not classes. So, I'll try to find a way to modify somehow the code in order to have id instead on classes.
Also, I'll try to transform and implement in ajaxify.min.js file, the page-container element; jQuery('#page-container').ajaxify(); I'll come back with news.
LE2: I've tried to implement the solution using id's instead of classes but still, the pages are not loading correctly.
At this point we have ajax.min.js file updated with these lines:
(function($){
jQuery(document).ready(function(){
jQuery('#page-container').ajaxify({requestDelay:400,forms:false});
});
})(jQuery);
Also, I've modified the theme file to have id=page-container instead if class=page-container.
In these conditions, on menu click, the links are changed (like it should), menu/ logotext elements seems to working almost fine (sometimes get skippy changing position), but the content is not loading correctly in all cases; Same here, everything is getting back to normal on manual page refresh (f5), but doesn't help.
LE3: It looks like the conflict is (at least) between Revolution Slider plugin and Ajaxify.
errormessage="Revolution Slider Error: You have some jquery.js library include that comes after the revolution files js include." ;="" +=" This includes make eliminates the revolution slider libraries, and make it not work." "<="" span="">"
Site live link here. Any thoughts / alternative in this area? (not interested in using other different platforms, different WordPress themes, etc. just a workaround in this existing situation)
LE4: As far as I can see, there are many users that voted up the Jake Bown answer that could be indeed a solution; but I can't find the reason that didn't work correctly implemented into my theme (without errors) live link here The elements logotext / menu are still fading on refresh, are not kept non-refreshed. Any thoughts #Jake Bown / anyone?
LE final.
Buzinas delivered the closest answer for my needs, taking in consideration my site environment (plugins installed, etc).
From what you said I think I might have found the solution you're looking for - you want to load content dynamically whilst keeping the logo and navigation untouched? If so, this might be what you're looking for.
In the example, the pages are loaded in from a div within the page but could be used to load another URL or file:
$('.viewport ul li a').on('click', function(e) {
e.preventDefault();
var link = this.hash.substring(1, this.hash.length);
if($('.'+link).length) {
$('.viewport span.body').html($('.'+link).html());
}
});
TL;DR
I've created a plunker for you, take a look, and play with it as long as you can. You'll learn a lot from it!
I think you're trying too many things here, but didn't try the simplest:
The main goal is to keep non-refreshed the logotext and the menu ,without clipping on page refresh or while the content is loading from a page to another. Also the menu state should be preserved from a page to another.
If you want to do that, there are a few steps:
Create a 'master' page, that we're going to call index.html from now on.
So, our index must have the static part of our page, e.g menu, logo, footer etc.
Then, our 'subpages' must be cut down (no html, head, body, script, style tags, only the content that should be showed into our master page).
That done, now we must change our links to use AJAX instead of doing full refresh:
/* we add a 'click' event handler to our menu */
document.getElementById('menu-menu-2').addEventListener('click', function(e) {
var el = e.target;
/* then, we see if the element that was clicked is a anchor */
if (el.tagName === 'A') {
/* we prevent the default functionality of the anchor (i.e redirect to the page) */
e.preventDefault();
/* we show our spinner, so the user can see that something is loading */
spinner.classList.remove('hidden');
/* and we call our AJAX function, passing a function as the callback */
ajax(el.href, function(xhr) {
/* we get our main div, and we replace its HTML to the response that came
from the AJAX request */
document.getElementById('main').innerHTML = xhr.responseText;
/* since the request was finished, we hide our spinner again */
spinner.classList.add('hidden');
});
}
});
Ok, now our pages are already working via AJAX, and not reloading our static content.
But now, we see that we have some issues. For example, if someone tries to open one of our pages directly via URL, he'll see unstyled page, without the menu/logo etc. So, what should we do?
We have a few more steps now:
Simulate that our links are effectively transfering between pages using the History API:
/* inside our ajax callback, we save the fake-redirect we made into the pushState */
ajax(el.href, function(xhr) {
document.getElementById('main').innerHTML = xhr.responseText;
/* save the new html, so when the user uses the back button, we can load it again */
history.pushState({
html: main.innerHTML,
title: el.textContent + '| neuegrid'
}, '', el.href);
/* (...) */
});
/* and outside it, we add a 'popstate' event handler */
window.addEventListener('popstate', function(e) {
/* so, if we've saved the state before, we can restore it now */
if (e.state) {
document.getElementById('main').innerHTML = e.state.html;
document.title = e.state.title;
}
});
And we need that when the user enters directly to another page, e.g about-us, we redirect him to the index.html, and then load the about-us page from there.
So we create a redirect.js file, and we reference it in all of our
subpages:
/* save the page that the user tried to load into the sessionStorage */
sessionStorage.setItem('page', location.pathname);
/* and them, we redirect him to our main page */
location.replace('/');
And then, in our index.html page, we see if there is any page in the sessionStorage, and we load it, if there is, otherwise we load our home page.
var page = sessionStorage.getItem('page') || 'home';
/* we look into the menu items, and find which has an href attribute
ending with the page's URL we wanna load */
document.querySelector('#menu-menu-2 > li > a[href$="' + page + '"').click();
And that's it, we're done now. Take a look at the plunker I've been making to you.
And play with it as long as you can, so you'll learn a lot from it.
I hope I could help you! :)
Note: Just for reference, this is our ajax function:
function ajax(url, callback, method, params) {
if (!method) method = 'GET';
var xhr = new XMLHttpRequest();
xhr.open(method, url);
if (callback) xhr.addEventListener('load', function() {
callback.call(this, xhr);
});
if (params) {
params = Object.keys(params).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
xhr.send(params);
} else {
xhr.send();
}
}
GOING AJAXED WITH WORDPRESS
demo: http://so.devilmaycode.it/how-to-keep-elements-non-refreshed/
follow these simple steps (let's take as example theme "twentyfifteen" on the WP templates folder):
edit single.php, page.php, index.php and all other pages having get_header() and get_footer() functions and replace it respectively with below code:
NOTE: this is important because if someone (ex: search-engine) reach your pages directly from the link, it is still fully available and 100% working. (useful for SEO)
<?php
//get_header()
if(!isset($_REQUEST['ajax'])){
get_header();
}
?>
<!-- other code --->
<?php
//get_footer()
if(!isset($_REQUEST['ajax'])){
get_footer();
}
?>
open the header.php add the below code inside the <head> section at the very end
<script>
!(function($) {
$(function() {
$('.menu-item a, .widget-area a, .page_item a').on('click', function(e) {
e.preventDefault();
var href = this.href;
var query = href ? (href + (!/\?/g.test(href) ? '?' : '&') + 'ajax=1') : window.location;
/* IMPLEMENT SOME LOGIG HERE BEFORE PAGE LOAD */
/* ex: kill instance of running plugins */
$('#content').hide().empty().load(query, function() {
/* IMPLEMENT SOME LOGIG HERE AFTER PAGE IS LOADED */
/* ex: refresh or run a new plugin instance for this page */
jQuery(this).show();
});
});
});
})(jQuery);
</script>
in the header.php file put the code below at the end of the file, 90% of times you need it under the navigation. In this case we already have this on the "twentyfifteen" theme.
NB: most probably you have the opening tag <div id="content" class="site-content"> inside the header.php file and the closing tag </div> on the footer.php file, this doesn't matter, you can leave it as is.
<div id="content"></div>
NOTE: consider this a proof of concept; it may work as is, but you still need to tailor it to suit your needs; you may need to:
Add a menu (in case it is not already set) by going under Appeareace > Menus > [check Primary Menu] > Save Menu in order to activate the menu. it's tested and working.
You may want to add some other class to the jQuery function like .widget-area a in order to ajax also widget links.
if you are using 3d party plugins you may need to ensure that all dependencies of each plugin are loaded also on the main page from where you want everything is displayed without refreshing content.
you may need to check and kill those 3d party plugin before a new page load and run or refresh plugin needed in the loaded page.

Replacing a whole webpage with alternative content (HTML + CSS + JS)

I am facing a problem that I am sure is pretty common. I found many solutions to this problem, and they all have their pros and cons. I'll post what I found here (which I believe will be useful to others), and I hope you'll point me in the right direction.
Essentially, this is my scenario:
I have a webpage in PHP: http://example.com/page_with_content_a_or_b.php.
This page returns Content A when no POST parameters are specified, and Content B if there are.
Assume a user connects to my page typing the previous URL in her browser (a GET request).
My server returns the page with Content A.
The user's web browser, via JavaScript, decides to replace Content A with Content B.
The question: How does the JavaScript replace the contents?
Well, as I've said, I've been looking for different solutions, but none seems perfect.
In order to discuss each possible solution, let me introduce you the resulting HTML code of each version:
HTML of Content A
<html>
<head>
<link rel="stylesheet" type="text/css" href="style_A.css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="gallery-animator.js"></script>
</head>
<body>
<div class="gallery"><!-- images here --></div>
<p>Content A</p>
<script type="text/javascript" src="content-b-loader.js"></script>
</body>
</html>
HTML of Content B
<html>
<head>
<link rel="stylesheet" type="text/css" href="style_B.css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="gallery-animator.js"></script>
</head>
<body>
<div class="gallery"><!-- images here --></div>
<p>Content B</p>
</body>
</html>
Differences between both versions
As you can see, in the example both versions are quite similar, but not identical. In general, these are the differences I might encounter:
All or some or none imported stylesheets may be different.
All or some or none imported javascripts may be different.
There might be differences with inline stylesheets and/or javascripts.
The content is different, but it may differ a little bit only or be completely different.
Content B does not includes the script for loading itself (last script in Content A).
Possible Solutions
Replacing Content with document.open(), document.write(), and document.close()
The first solution I implemented is the following:
content-b-loader.js (option 1)
$(document).ready(function() {
$.ajax({
type: 'POST',
url: window.location.href,
data: { load_content_b: 'true' },
success: function( html ) {
document.open();
document.write(html);
document.close();
}
});
});
Apparently, the solution works properly. However, there are situations in which I have problems. In my example, for instance, both contents load a script named gallery-animator.js. Assuming this script is the following:
gallery-animator.js
var galleryInterval = setInterval(function() {
// Fade out current image and fade in the next one
$("body > div.gallery > img")...
}, 5000);
after executing the script in content-b-loader.js there are two timeouts animating the gallery. As a result, the animation looks like a mess (two images moving at the same time, or not working at all).
It looks like the sequence document.open(), document.write(html), and document.close() does not stop and replace the original scripts.
Redirecting with POST data (using a form)
Another solution is doing a redirection described in this previous question. The solution works like a charm: on the one hand, I load the URL I need to load with the required POST data, which means I'll get Content B, and on the other hand, Content B is loaded in a "new page", which means that the scripts loaded by Content A are no longer there.
The problem here? If I refresh the page with Content B, I get a warning stating that "POST data is about to be resubmitted". This is undesirable, because it looks confusing for the user (I don't want her to know she had been redirected to a new page).
I know there's a solution called PRG (Post-Redirect-Get) which avoids this particular issue. However, it requires Content B to be accessible using a GET request (using GET params or COOKIES, neither of which I can use).
Using iframes
The last solution I've found is also interesting. Basically, it hides (or empties) the body from Content A, adds an iframe in the page, and loads Content B inside it:
content-b-loader.js (option 3)
$(document).ready(function() {
$.ajax({
type: 'POST',
url: window.location.href,
data: { load_content_b: 'true' },
success: function( html ) {
$("body").css('', ''); // Remove all paddings and margins
$("body").empty();
$("body")append('<iframe id="content" seamless="seamless"' +
'src="anchor.html"></iframe>');
// Initialize vars in anchor.html and call the redirect functions
document.getElementById('content').contentWindow.url = window.location.href;
document.getElementById('content').contentWindow.options = {
load_content_b: 'true'
};
document.getElementById('content').contentWindow.redirect();
}
});
});
anchor.html
This page implements the second solution (it uses a POST redirect).
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.redirect.min.js"></script>
<script type="text/javascript">
var url;
var options;
function redirect(){
$().redirect(url, options, 'POST');
}
</script>
</head>
<body></body>
</html>
By making the iframe as big as the window view, I can show the alternative content. If the user refreshes the webpage, the page that is refreshed is the "container" page (the one that originally had Content A), so no warnings appear at all.
The problems I am facing with this solution, however, are:
Users can disable iframes. How do I detect whether iframes are enabled or disabled?
When the user clicks a link in the frame (or submits a form), the "new page" is opened inside the iframe. This is not what I want: I want it to be opened in the main window. How do I do this? I know that there is the base directive for links... but what about forms? And JavaScript code that performs a redirection?
Does everything work properly inside iframes? Responsive themes, javascripts, ... As far as I can tell, they do, but I ignore whether users can limit what iframes can do.
TL;DR - Conclusions
I have a page http://example.com/page_with_content_a_or_b.php. The page returns Content A when accessed using a GET request, and returns Content B when accessed using POST. When user types the URL, she gets Content A, and Content B is loaded using JavaScript.
All solutions entail problems:
With document.open(), document.write(), document.close(), scripts get messed.
With POST redirections, refreshing the page popups a warning
With iframes, they are not always available, and I am somehow "stucked" inside them.
Any ideas? Am I missing something? Is there a preferred way to do what I'm trying to do?
Thank you very much!
There's a hacky fix for the problem with messy script behavior in your first solution. Assuming that the script-related problem only occurs when using timeouts (I don't know if there are other scenarios in which things can go wrong....), there's an easy way to clear all timeouts. Just add this code:
var id = window.setTimeout(function() {}, 0);
while (id--)
window.clearTimeout(id);
A POST request should do things which change or affect data. Thus it makes sense to prevent the user from refreshing and that should be desirable behavior, I am confused whether you're doing an actual post request or otherwise why is redirecting to a POST page is so problematic?
Either way, regarding your <iframe> solution, let me give some suggestions. "Disabling iframes" is indeed technically possible on some browsers, but to do such a thing you have to either dive in about:config or very deep in the IE menu and it's entirely impossible on Chrome by default. So yeah, truth be said, I would not concern myself with that whatsoever, just like nowadays most sites do not concern themselves with users who disable javascript (any user with disabled iframes will probably have javascript disabled as well btw), simply because it's too rare to concern yourself with and it's one of those choices where you have to face the consequences yourself. Now, I was planning on directing you to the <base> tag as well, just realizing now that you already mentioned it in your post. Either way, the tag will work for forms as well, but not for javascript 'links'.
All in all I would advice you to rethink whether the page should be POST, if so, then you should just go with the warning and otherwise rework it to be just another GET page.
I guess I'm missing something, because I don't clearly understand what do you mean by "The user's web browser, via JavaScript, decides to replace Content A with Content B", but:
If you know in advance the parameters of the elements whose content you'd like to replace, wouldn't a simple case by case replacement work?
<html>
<head>
<link rel="stylesheet" type="text/css" href="style_A.css">
</head>
<body>
<div class="gallery"><!-- images here --></div>
<p class="content">Content A</p>
</body>
<!-- This could be content-b-loader.js -->
<script>
var $stylesheet = document.getElementsByTagName('link')[0];
$content = document.querySelectorAll('.content')[0];
if ( $stylesheet && $content ) {
if ( $stylesheet.getAttribute('href') == 'style_A.css' ) {
$stylesheet.setAttribute('href', 'style_B.css');
}
$content.innerHTML = 'Content B';
}
</script>
</html>

Simple Javascript Doesn't Work Right

I use the tabber script shown on http://www.barelyfitz.com/projects/tabber/ to provide a tabbed page. Generally it works well, and my only complaint is that the tabs don't show until the content has fully loaded, and then there is a jump as the screen writes itself properly. (See www.littlehotels.co.uk/spain/noves.php for an example of what I mean.)
I thought the solution would be to hide the div containing all the tabbed content like this
<div class="tabber" id="tabber" style="display:none">
and then reveal it with a small javascript function which is called by
<body onLoad="ShowTabber()">
The javascript itself is
<script type="text/javascript">
function ShowTabber() {
document.getElementById('tabber').style.display = "block";
}
</script>
My little function appears to stop the external javascript (tabber.js) from working because the page displays the content of all the tabs in line, without the the tabs themselves at the top. This is the same result as if I delete the reference to the external script from the of the page.
What am I doing wrong?
More explanation:
When the tabber.js file is missing, the page displays the content of all the tabs one after the other(as you would expect). Running the script as explained above has exactly the same effect; hence I am concluding that the script blocks the main javascript from running.
'onLoad': function(argsObj) {
/* Display an alert only after tab */
if (argsObj.tabber.id == 'tab') {
alert('Finished loading tab!');
}
}
By default select a tab.Then after completion loading that tab it will show a message.
see here
Well, I solved the problem (sort of) with jQuery, but it has now raised another problem.
In response to PSR, I looked more deeply into jQuery. It would have been too complicated to change over to .tabs(), but I did use jQuery to hide and show some divs at the appropriate moments.
I placed a simple little line in fron of the tabber div to show a "Loading" message.
<div id="loading" align="center" style="position:relative;top:70px"><h6>Loading ...</h6></div>
Then I put this script in the head, under the jQuery line.
<script type="text/javascript">
$(document).ready(function(){
$("#tabber").hide();
$("#loading").hide();
$("#loading").fadeIn(1000);
});
$(window).load(function(){
$("#loading").hide();
$("#tabber").fadeIn(300);
});
function checkResize(id){
var win=document.getElementById(id).contentWindow.document.body.scrollHeight;
alert(win);
}
</script>
That works fine, but a couple of the tabs have iframes for their content, and this script breaks autoResize script I use on those iframes. I'll open a new question to see if anyone has an answer to that.

How to realize screens / views with JavaScript / Jquery easily?

I'm sure I'm missing something pretty basic, but I have just started to get myself up to speed on jQuery and Javascript programming. Previously I was doing server side programming with PHP.
I'm now in the middle of creating a prototype for HTML5 webapp, where I would like to have different screens. Now with PHP that was pretty easy, I could just used server side templates like Smarty and be done with it.
However to make my app more webapp like, I would like to dynamically change between screens without having to reload the window.
I have looked into several options that might be anwsers to my question, but I'm not sure whether I'm on the right track.
I have checked for example JsRender, JsViews or even the pure jquery load command.
But what I'm not sure is whether these things would allow me to have something like this:
HEADER_PART
MAIN_CONTENT
FOOTER_PART (also contains links to common JS files that I use)
I would like to dynamically update the MAIN_CONTENT part. Currently my application is only one page, and all my custom logic that belongs to that page is in one JS file. In this JS file, I use a simple $(function() { ... to load my page, so whenever it gets loaded, parts of my page get updated asyncronously. This is fine, since all my blocks in this certain page would have to be loaded when that one page gets loaded.
But what if I have a link, like main.html#otherscreen, and when I click that screen, I would like to change my MAIN_CONTENT and also run another page load specific JS that handles blocks on that other screen, not the first page?
I know I could still use probably server side templating and load my pages using AJAX requrests, but again, not sure whether that is the right approach.
Could you please enlighten me? :)
Thanks & best regards,
Bence
Check out jQuery.load(). Using this function you can dynamically load content into a div on the page, which is what I think you want to do. Just find the div on the page you want to load content into and call
$('#mydiv').load(url, data, function(response){
//do something once it's done.
});
Per your comments...
This is actually very easy. .load() should replace the content in the div (I think. If not, just call .empty() first). Of course you could get fancy and add effects, like
function changePages(url) {
$('#mydiv').fadeOut('fast', function() {
$(this).load(url, function(response){
$('#mydiv').fadeIn('fast');
});
});
}
To handle things like the hash in the URL, in your click event you have to make sure you first call e.preventDefault():
$('#mylink').click(function(e){
e.preventDefault(); //e is a jquery event object
var link = $(this);
var hash = link.attr('href'); // get the hashtag if the href is '#something'
changePages(someUrl + hash);
});
For dynamic loading of data into the page without changing your header and footer you should use jQuery's AJAX function. It allows you to post requests to the server and receive data back without reloading the page. A simple example would be something like:
<html>
<head>
<title>Example</title>
<!-- Assuming jQuery is already referenced -->
<script type="text/javascript">
$('span.buttonish').click(function(){
$.ajax({
// The URL can be a file or a PHP script of your choosing
// it can also be pure HTML without the <html> tags as they
// are already in your file
url: 'path/to/the/file/that/return/data',
success: function(receivedData) {
// The received data is the content of the file or the return
// data of the script and you can use it as you would with any data
$('#content').html(receivedData);
}
});
});
</script>
</head>
<body>
<div id="header">
<!-- Something -->
</div>
<div id="content">
<span class="buttonish">Click me to change the text... </span>
</div>
</div id="footer">
<!-- Something -->
</div>
</body>
<html>

Categories

Resources