What comparable Javascript function can reference a file like PHP's include()? - php

What is the best way to reference or include a file using Javascript, looking for the closest functionality of PHP's include() ability.

I would check out Javascript equivalent for PHP's include:
This article is part of the 'Porting
PHP to Javascript' Project, which aims
to decrease the gap between developing
for PHP & Javascript.
There is no direct equivalent - you can either go with the function I linked above or use document.write to write out a new script tag with a src pointing to the file you wish to include.
Edit: Here is a rudimentary example of what I mean:
function include(path) {
document.write(
"<script type=\"text/javascript\" src=\"" + path + "\"></script>"
);
}
Edit 2: Ugh, what an ugly example - here is a better one:
function include(path) {
script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", path);
if (head = document.getElementsByTagName("head")[0]) {
head.appendChild(script);
}
}
document.write is a hackish way of doing things and I shouldn't have recommended it. If you go with one of my examples please use the second one.

I have a script that I wrote a while back (using Mootools) that allows for one to include javascript files on the fly (with a callback function after its loaded). You can modify it to work the library of your choice if you choose.
Note the gvi prefix is just my namespace and that gvi.scripts is an array containing all the javascript files currently included on the page, those can be removed if you want. Also, the filename function can be removed, that was just added to make my life easier [require('some-script') vs require('js/some-script.js')].
//if dom isn't loaded, add the function to the domready queue, otherwise call it immediately
gvi.smartcall = function(fn) {
return (Browser.loaded) ? fn() : window.addEvent('domready', fn);
}
//For dynamic javascript loading
gvi.require = function(files, callback, fullpath) {
callback = callback || $empty;
fullpath = fullpath || false;
var filename = function(file) {
if (fullpath == true) return file;
file = ( file.match( /^js\/./ ) ) ? file : "js/"+file;
return ( file.match( /\.js$/ ) ? file : file+".js" );
}
var exists = function(src) {
return gvi.scripts.contains(src);
}
if ($type(files) == "string") {
var src = filename(files);
if (exists(src)) {
gvi.smartcall(callback);
} else {
new Asset.javascript( src, {
'onload' : function() {
gvi.scripts.push(src);
gvi.smartcall(callback);
}
});
}
} else {
var total = files.length, loaded = 0;
files.each(function(file) {
var src = filename(file);
if (exists(src) && loaded == total) {
gvi.smartcall(callback);
} else if (exists(src)) {
loaded++;
} else {
new Asset.javascript( src, {
'onload' : function() {
gvi.scripts.push(src);
loaded++;
if (loaded == total) gvi.smartcall(callback);
}
});
}
});
}
}
And you call it like
gvi.require('my-file', function() {
doStuff();
});
//or
gvi.require(['file1', 'file2'], function() {
doStuff();
});

jQuery has a plugin for this: http://plugins.jquery.com/project/include

Instead of using javascript and making our work more complex, we have pretty easy way to include external file using the IFRAME tag in HTML.
**
<iframe src="....../path/filename.html" width="" height="">
**
We can also control iframe using CSS if even more customization required .

Related

Dynamic div swapping using php/jquery resulting in a page recursion

I am working on making a dynamically loaded website using some php code to swap out content from various other files. While on top of that I am using jquery to beautify this swap out.
Relevant PHP:
<?php
// Set the default name
$page = 'home';
// Specify some disallowed paths
$disallowed_paths = array('js.php','css.php','index.php');
if (!empty($_GET['page'])){
$tmp_page = basename($_GET['page']);
// If it's not a disallowed path, and if the file exists, update $page
if (!in_array($tmp_page, $disallowed_paths) && file_exists("{$tmp_page}.php"))
$page = $tmp_page;
}
// Include $page
if(!file_exists("$page.php")){
$page = 'home';
}
else{
include("$page.php");}
?>
Relevant jquery:
$(function (a) {
var $body = $('body'),
$dynamo = $('.dynamo'),
$guts = $('.guts');
$body.fadeIn('slow');
if (history.pushState) {
var everPushed = false;
$dynamo.on('click', 'a', function (b) {
var toLoad = $(this).attr('href');
history.pushState(null,'',toLoad);
everPushed = true;
loadContent(toLoad);
b.preventDefault();
});
$(window).bind('popstate', function () {
if (everPushed) {
$.getScript(location.href);
}
everPushed = true;
});
} // otherwise, history is not supported, so nothing fancy here.
function loadContent(href) {
$guts.hide('slow', function () {
$guts.load(href, function () {
$guts.show('slow');
});
});
}
a.preventDefault();
});
What is happening is when I link to a page using ?page=about it will work but it will instead of just swapping out the content it will load the entire page including the content inside the dynamically loaded div.
If I were to link straight to about.php it would work beautifully with no fault whatsoever, but anybody who wanted to share that link http://example.com/about.php would get just the content with no css styling.
If I were to change the jquery in "loadContent" to:
$guts.load(href + ' .guts', function () {
EDIT 1:
, ' .guts'
to
+ ' .guts'
It would then work but any script, java, jquery, or the like would not work because it gets stripped out upon content load.
check out http://kazenracing.com/st3
EDIT 2:
It also seems to be that the site does not work properly in the wild either.
No background and none of the icons show up, but it still gets the general problem across.
I can fix that myself, it will just take some time. For now my focus is on the recursion problem.
EDIT 3: Site no longer needs to be worked on, problem never solved but we are letting that project go. So the link no longer is a valid URL.

Jquery replaceWith:replace one php file with another php file based on screen resolution

I need to be able to replace a php file with another php file based on screen resolution. This is what I have so far:
<script type="text/javascript">
function adjustStyle(width) {
width = parseInt(width);
if (width = 1920) {
$('book.php').replaceWith('book2.php');
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
</script>
which obviously isn't working-- any ideas? Thank you in advance for any help received.
UPDATE
Is this at all close (to replace the book.php line)?
{ $("a[href*='book.php']").replaceWith('href', 'book2.php'); };
Second Update to reflect input gathered here
function adjustStyle(width) {
width = parseInt(width);
if (width == 1920) {
$('#bookinfo').replaceWith(['book2.php']);
$.ajax({
url: "book2.php",
}).success(function ( data ) {
$('#bookinfo').replaceWith(data);
});
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
}
}
I have not seen the use of replaceWith in the context you put it in. Interpreting that you want to exchange the content, you may want to do so my using the load() function of jQuery.
if(width == 1920){
$("#myDiv").load("book1.php");
} else {
$("#myDiv").load("book2.php");
}
Clicking on the button replaces the content of the div to book2.php.
The first problem is I don't think that you are using the correct selectors. If you have the following container:
<div id="bookContainer">Contents of book1.php</div>
The code to replace the contents of that container should be
$('#bookContainer').replaceWith([contents of book2.php]);
In order to get [contents of book2.php] you will need to pull it in by ajax using the following code I have also included the line above so that the data from book2.php will be placed into the container:
$.ajax({
url: "http://yoururl.com/book2.php",
}).success(function ( data ) {
$('#bookContainer').replaceWith(data);
});.
I haven't tested this so there might be an issue but this is the concept you need to accomplish this.
First off... using a conditional with a single = (equal sign) will cause the condition to always be true while setting the value of variable your checking to the value your checking against.
Your condition should look like the following...
if (width == 1920) { // do something }
Second, please refer to the jQuery documentation for how to replace the entire tag with a jquery object using replaceWith()... http://api.jquery.com/replaceWith/
I would use a shorthand POST with http://api.jquery.com/jQuery.post/ since you don't have the object loaded yet...
In short, my code would look like the following using $.post instead of $.ajax assuming I had a tag with the id of "book" that originally has the contents of book.php and I wanted to replace it with the contents of book2.php...
HTML
<div id="book">*Contents of book.php*</div>
jQuery
function onResize(width) {
if (parseInt(width) >= 1920) {
$.post('book2.php',function(html){
$('#book').html(html).width(width);
});
}
else {
$.post('book.php',function(html){
$('#book').html(html).width(width);
});
}
}
Hope this helps.

Script wont call function in Google Chrome

I have a script that pops up a div element when a anchor tag is clicked
echo '<h2>' . $row['placename'] . '</h2>';
It's echoed from a PHP script, and is working fine in FF and IE(9).
But chrome won't run it, atleast on ver. 18.0.1025.168 m
The popup(divid); event fires when I click it, but it doesent complete the function calling inside the script the function is in.
var width_ratio = 0.4; // If width of the element is 80%, this should be 0.2 so that the element can be centered
function toggle(div_id) {
var el = document.getElementById(div_id);
if ( el.style.display == 'none' ) { el.style.display = 'block';}
else {el.style.display = 'none';}
}
function blanket_size(popUpDivVar) {
alert(popUpDivVar);
if (typeof window.innerWidth != 'undefined') {
viewportheight = window.innerHeight;
} else {
viewportheight = document.documentElement.clientHeight;
}
if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
blanket_height = viewportheight;
} else {
if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
blanket_height = document.body.parentNode.clientHeight;
} else {
blanket_height = document.body.parentNode.scrollHeight;
}
}
var blanket = document.getElementById('blanket');
blanket.style.height = blanket_height + 'px';
var popUpDiv = document.getElementById(popUpDivVar);
popUpDiv_height=0;
popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerHeight;
} else {
viewportwidth = document.documentElement.clientHeight;
}
if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
window_width = viewportwidth;
} else {
if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
window_width = document.body.parentNode.clientWidth;
} else {
window_width = document.body.parentNode.scrollWidth;
}
}
var popUpDiv = document.getElementById(popUpDivVar);
window_width=window_width/2;
window_width = window_width * width_ratio;
popUpDiv.style.left = window_width + 'px';
}
function popup(windowname) {
alert(windowname); // THIS WORKS
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
}
The last function in that script is the one that is called first. I put an alert box in it to verify that it was fired. BUT, I put an alert box in the next function that it calls (blanket_size), and it did not fire, as I had the alert box on the first line in the function. It did not fire.
I simply have no clue why. The weird thing is that this stuff works in other browsers, but not chrome. Any ideas?
Thanks!
Edit: And I also verified that the parameter value passed into the popup() function (the 'windowname' param) is valid/has a value. It contains the ID of a DIV that is in the HTML document, and it's not dynamically created.
Edit 2: Ok, I got the script running when and ONLY when I add an alert box with the parameter value in it (windowname) to the popup(windowname) function. But if I remove that box, it stops working again.
Edit 3:
Got no errors on the debugger at all. But now I'm even more confused. After a great deal of tries, it seems like it's working with the alert box at random! Sometimes works, and sometimes not.
Final Edit
Changed logic to jQuery. Should have done this long ago!
// Open property
$(".property-open-link", ".yme-propertyitem").live('click', function() {
$("#yme-property-pop").css({'display': 'block', 'z-index': '9999' });
$("#blanket").css({'display': 'block', 'height', getBlanketHeight(), 'z-index': '1000' });
loadproperties('open', $(this).closest(".yme-propertyitem").attr("id"));
});
// Close property button
$("#yme-property-close").live('click', function() {
$("#yme-property-pop").css('display', 'none');
$("#blanket").css('display', 'none');
});
Couple of things to clear up first:
It really helps if you create a way for us to interact with your
code, especially as you've pasted PHP code here, instead of plain
HTML
Is there a reason why you're not using a library to handle your DOM
interactions? It will make your code more concise and take away some
possible failure points when it comes to cross-browser code.
Right,
I'm a little unsure why your code isn't working in Chrome. I set up a demo in jsfiddle and it seems to work fine.
You'll notice I'm not attaching the events in onclick attributes on the <a/> element, and neither should you. This could be where the problem lies.
Currently, the code in the jsfiddle alerts as expected and only fails when it fails to find a relevent DOM node in toggle.
Note:
addEventListener in the example is not cross-browser, which is another reason to use a DOM library.

Multiple fbAsyncInit's?

In my site I'm using asynchronous loading of the Facebook JS SDK. To actually set it up I use the standard FB.init inside of window.fbAsyncInit function.
However the issue is that in my site this function is on every single page. However when I'm in a subpage I can't directly add to the JS function due to the design of my site, I have to copy and paste the whole function and add my bits.
I don't think multiple fbAsyncInit's are possible, so whats the best way to implement this?
You can use this instead to check if you already have a fbAsyncInit and chain it toghether in that case:
var oldCB = window.fbAsyncInit;
window.fbAsyncInit = function(){
if(typeof oldCB === 'function'){
oldCB();
}
//Do Something else here
};
Sometimes the facebook api can call fbAsyncInit before your second fbAsyncInit has even started. This will fix that case:
if (window.fbAsyncInit.hasRun === true) {
setup(); // do something
} else {
var oldCB = window.fbAsyncInit;
window.fbAsyncInit = function () {
if (typeof oldCB === 'function') {
oldCB();
}
setup(); // do something
};
}
there is a "static" property in fbAsyncInit
Try below
if (window.fbAsyncInit && window.fbAsyncInit.hasRun) {
// do sth
}

Is there a better way to track pagination with hashtags?

Using a hashchange event I'm detecting when a user clicks the back button in a browser and changing the URL accordingly. Is there a better way to do this for pagination? I'm currently changing the URL after a user clicks my pagination control like so:
$(".pager").click(function(){
var start = null;
if ($.browser.msie) {
start = $(this).attr('href').slice($(this).attr('href').indexOf('#')+1);
}
else {
start = $(this).attr('href').substr(1);
}
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
return false;
});
My javascript to detect the back button looks like this:
function myHashChangeCallback(hash) {
if (hash == "") {
$("#loadImage").show();
var no_cache = new Date().getTime();
$('#main').load("home.php?cache=" + no_cache, function () {
$("#loadImage").hide();
});
return false;
}
else {
// adding code to parse the hash URL and see what page I'm on...is there a better way?;
}
}
function hashCheck() {
var hash = window.location.hash;
if (hash != _hash) {
_hash = hash;
myHashChangeCallback(hash);
}
}
I currently plan on checking each hashtag and the value to see what page I should load unless there is a better more efficient way.
Any thoughts or suggestions?
The jQuery Address plugin does this very well. Once setup it provides a series of logical navigation events which you can hook into. It also has very good support for history.pushState() which eliminates the need for hashtags in newer browsers and has equally good fallback support for those browsers that do not support pushState.
A simple implementation would look like this:
// Run some code on initial load
$.address.init(function(e) {
// Address and path details can be found in the event object
console.log(e);
});
// Handle hashtag/pushState change events
$.address.change(function(e) {
// Do more fancy stuff. Don't forget about the event object.
console.log(e);
});
// Setup jQuery address on some elements
$('a').address();
To enable pushState() support pass an argument to the script like so:
<script type="text/javascript" src="jquery.address-1.3.min.js?state=/absolute/path/to/your/application"></script>

Categories