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
}
Related
well the question is enough explained can it be done.
what I am trying to do is to get data from a popup and onclose I want to send the content I retrieved to a php controller for processing.
But I dont want to use jquery library, because it is creating a conflict for me.
Update
window.onbeforeunload = confirmExit;
function confirmExit()
{
var a = document.getElementsByTagName("div");
for (i = 0; i < a.length; i++) {
if(a[i].className == 'Ymacs-frame-content'){
var b = a[i].getElementsByTagName("div").innerHTML;
//alert(b);
}
}
//Ajax should be here
window.onbeforeunload = reloadOpener;
if (top.opener && !top.opener.closed) {
try {
opener.location.reload(1);
}
catch(e) { }
window.close();
}
}
window.ununload=function() {
reloadOpener();
}
You can just use jquery-less AJAX:
var a = new XMLHttpRequest();
a.open("GET","myscript.php?var=foo&othervar=bar",true);
a.onreadystatechange = function() {
if( this.readyState == 4) {
if( this.status == 200) {
// data sent successfully
// response is in this.responseText
}
else alert("HTTP error "+this.status);
}
};
a.send();
Alternatively, you can create an iframe tag and point it to the right page. You can even create a form and post it to the frame if needed.
You can do it in javascript without using jQuery since that is all jQuery does in the background. You will need to look at the different ways IE does it compared to other browsers though.
Yes, XMLHttpRequest, but you'll need to account for differences in browsers, which jQuery does for you.
I just went through this. The only way to use Javascript to pass info to PHP is by using XMLHttpRequest, or at least if there is another way I did not find it. It has to do with the fact that PHP renders on the server side, and Javascript isn't executed until after it is served to the client...unless you use the XHR which is...AJAX.
I have a page within wordpress that I want to password protect via a user role plugin. Everything works fine on straight forward pages but I have a page with window.onload = function() { that completely overrides the password function.
I want the page to load immediately after it's checked to see if the user is logged in or not.
Update:
I'm using this plugin and I just have the function:
<script type="text/javascript">
(function() {
window.onload = function() {
var map = new google.maps.Map(document.getElementById('map'), options);
...
} } )
</script>
Which then loads on this div:
<div id="map" style="width:100%; height:100%"></div>
You have to use addEventListener or attachEvent to load multiple functions. If you want to use window.onload = .., use the code in the last else block at the function below:
function addEvent(name, func) {
if (window.addEventListener) {
window.addEventListener(name, func, true);
} else if(window.attachEvent) {
window.attachEvent('on' + name, func);
} else {
var other_func = typeof window['on'+name] == "function" ? window['on'+name] : function(){};
window['on' + name] = function(ev){
func(ev);
other_func(ev);
}
}
}
addEvent('load', function(){
//Load function
});
Instead of assigning it directly to the onload property add it as an event listener
https://developer.mozilla.org/en/DOM/element.addEventListener
You'll need to use attachEvent for IE versions < 9.
http://msdn.microsoft.com/en-us/library/ms536343(v=vs.85).aspx
If you're using a framework such as jQuery or Prototype this can be abstracted out so you don't need to worry about different browsers.
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>
I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.
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 .