I am having problems with using Ajax and Fancybox.js photo viewer together.
I have a website set up first as web 1.0 with the standard navigation with hyperlinks.
but for html5 browsers I'm am using javascript that creates a web 2.0 experience.
The javascript first highjacks the links onclick event which makes a XMLHttpRequest that calls a php script that parses the html and sends back just the part of the html that I want to replace. I am using pushState and popState to get the back and forward buttons to function.
It is working great, it creates the Ajax effect, while persevering all the advantages of web 1.0 including SEO, because the links as far as the search engine spiders are concerned the links are just standard links to standard html pages.
The problem is that one of the pages uses Fancybox.js to show photos, it works fine when the page is accessed via the standard url, but when the html is accessed via the Ajax scripts if breaks it.
Here is code for the Ajax,
if (history.pushState) {
function changeContent(url) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById('content').innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "getContents.php?url=" + url, true);
xmlhttp.send();
}
$(document).ready(function() {
var elems = null,
links = null,
link = null,
i;
elems = document.getElementById('nav');
links = elems.getElementsByTagName('a');
if (links) {
for (i = 0; i < links.length; i++) {
links[i].addEventListener("click", function(e) {
url = $(this).attr("href");
var pathArray = window.location.pathname.split( '/' );
var n = pathArray.length;
changeContent(url);
history.pushState(null, null, url);
e.preventDefault();
var urlstr = window.location,
index = /index/g,
program = /program/g,
photos = /photos/g,
testimonials = /testimonials/g,
about = /about/g,
contact = /contact/g;
if (program.test(urlstr)){
changeCurrentPage('#program');
document.title = "Our Programs Kolibri Daycare";
}else if (photos.test(urlstr)){
changeCurrentPage('#photos');
document.title = "Photos Kolibri Daycare";
slideShow();
}else if (testimonials.test(urlstr)){
changeCurrentPage('#testimonials');
document.title = "Tesimonials Kolibri Daycare";
}else if (about.test(urlstr)){
changeCurrentPage('#about');
document.title = "About Kolibri Daycare";
}else if (contact.test(urlstr)){
changeCurrentPage('#contact');
document.title = "Contact Kolibri Daycare";
}else {
changeCurrentPage('#home');
document.title = "Kolibri Daycare";
}
}, false);
}
}
window.setTimeout(function() {
window.addEventListener("popstate", function(e) {
var pathArray = window.location.pathname.split( '/' );
var n = pathArray.length;
if (pathArray[n-1]){
changeContent(pathArray[n-1]);
}else {
changeContent('index.html');
}
}, false);
}, 1);
});
}
and her is the script that calls Fancybox.js,
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$("a[rel=example_group]").fancybox({
'overlayShow' : false,
'cyclic' : true,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic'
});
});
//]]>
</script>
It is in the head section of the page.
When the html that has the photo links is brought in via Ajax the script that calls fancybox.js is not included. I have tried calling it in different places but nothing seems to work. Does anyone have any ideas?
You need to re-initialize fancybox on the new elements added from ajax. I'm not sure why you don't just upgrade the entire page to HTML5 and use some of the ajax functions provided by jQuery, but I think the re-initialization should be inserted after this line (not tested!):
document.getElementById('content').innerHTML = xmlhttp.responseText;
$('#content').find("a[rel=example_group]").fancybox();
Related
<script src="includes/fotorama.js"></script>
<div id="fotorama" class="fotorama">
<img src="images/6.jpg"/>
<img src="images/7.jpg"/>
<img src="images/8.jpg"/>
</div>
This works fine in the begining. Once i update the images via ajax call , Slider does not work.. Please help ..
This is a bad way to update the images in the fotorama. Still you can make it work by altering your onreadystatechange function:
function fun (str) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var $fotorama = $('#fotorama'),
api = $fotorama.data('fotorama');
if ($fotorama[0] && api) {
api.destroy(); // destroy previous instance
$fotorama[0].innerHTML = xmlhttp.responseText;
$fotorama.fotorama(); // make new one
}
}
};
xmlhttp.open('GET', "<?php echo site_url();?>home/s?regid=" + str, true);
xmlhttp.send();
}
A “good” way is to use the methods of the Fotorama API, load and push for example:
// Get access to the API
var fotorama = $('#gallery-id').data('fotorama');
// Overwirte all the photos
fotorama.load([
{img: '1.jpg', thumb: '1-thumb.jpg'},
{img: '2.jpg', thumb: '2-thumb.jpg'},
{img: '3.jpg', thumb: '3-thumb.jpg'}
]);
// Or push one to the end
fotorama.push({img: '4.jpg', thumb: '4-thumb.jpg'});
The image object may look like so:
{
img: '1.jpg',
thumb: '1-thumb.jpg', // if you are using the `nav:'thumbs'` option
full: '1-full.jpg', // separate image for the fullscreen mode
id: 'one', // custom anchor, used with the `hash:true` option
fit: 'cover', // override the global fit option
caption: 'The first one'
}
My first post
Im trying to call a rest webservice to populate my lov's dynamically using AJAX. It works fine for me in IE8 but not in chrome. I couldn't reach a particular line while executing that I mentioned in the below code. Am i missing anything. Please help.
07-24-2012 - I found the root cause for this issue. Its because of the application cache code specified in the html code. once i remove that the ajax call works fine. But my need is to make this page available in offline mode. Any suggestion on this to make the page available offline and also the ajax webservice calls works fine?. Thanks,
<script type="text/javascript">
var eleCount;
var xmlDoc;
function init() {
eleCount =0;
}
function populate()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
alert("Window for chrome");
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
alert("Else Window for IE");
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
}
var url = "http://localhost:7101/Mobile-MobileModel-context- root/jersey/Search/searchLov";
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var det = xmlhttp.responseText ;
if (window.DOMParser)
{
//I cannot reach this line while executing.
alert("This alert is not appearing");
var parser=new DOMParser();
xmlDoc=parser.parseFromString(det,"text/xml");
var x=xmlDoc.getElementsByTagName("fieldValue");
var txta =new Array();
....some code
}
}
else // Internet Explorer
{
alert("else window DOM parser for IE");
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(det);
...... some code
} // end for
} //end else for Other Browser (window.DOMParser)
} //end if Readystate 4 and Status 200
else{
}//else
}//close OnReadyStatechange Function
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
eleCount = eleCount + 1;
}//end Function Populate()
</script>
I made it working -- The problem arises whenever i added this line
<HTML manifest=../../demo.appcache> This code will download the files mentioned in the manifest file to the browser's application cache. When I remove this line the rest calls are working fine.
I have put together some code from various sources but javascript is somewhat unknown to me and I only seem to fail with the code I have so far..
What I want to do is convert every normal link on the page to ajax links and load the pages through ajax.
So far I only succeeded to transform the links from the initial page and load the content in a div. The problem is I don't have access to the content is loading in the div and the new content still has normal links instead of ajax.
Is there a way I can convert the new links within the content loaded in the div, every time the div changes?
Also what I don't know is, if the user clicks on the home button in the menu, it will load the content of index along with this script, and everything will become a loop. How can I prevent the code from loading in index if it loads inside the div?
If you suspect any other problems it may occur from this code can you please advice me what to change?
This is the code I have so far..
Thank you very much for any advice!
Inserted in the head tag:
<script type="text/javascript">
var xmlhttp;
if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else if(window.ActiveXObject){ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
else{ }
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4)
{ document.getElementById("contentarea").innerHTML = xmlhttp.responseText; }
else{ document.getElementById("contentarea").innerHTML = ""; }
}
function loadPage(url){
document.getElementById("contentarea").innerHTML = "";
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
</script>
Inserted somewhere in the body:
<div id="contentarea"></div>
Inserted right before the body ends:
<script>
var oP = document.getElementsByTagName("a");
var ctr=0;
while(ctr < oP.length){
var oldHref = document.getElementsByTagName("a")[ctr].href;
document.getElementsByTagName("a")[ctr].href="javascript:loadPage('"+oldHref+"');";
ctr++;
}
</script>
here ja go.. whipped this up for you.. you can use document.links to get all anchor tags. I'm doing this on 'contentArea' only. Everything inside (function () { will only be called when the document is ready. Then, in the onreadystatechange event I call the function again to set the click event on any anchors that are returned in the resposne.
<script type="text/javascript">
var xmlhttp;
function loadPage(url){
document.getElementById("contentarea").innerHTML = "";
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
var parseAnchors = function(){
var anchors = document.getElementById("contentarea").links; // your anchor collection
var i = anchors.length;
while (i--) {
var anchor = anchors[i];
anchor.onclick = (function(url) {
return function() {
loadPage(url);
return false;
};
})(anchors[i].href);
anchor.href = "#";
}
};
(function () {
if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else if(window.ActiveXObject){ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
else{ }
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4)
{ document.getElementById("contentarea").innerHTML = xmlhttp.responseText; }
else{ document.getElementById("contentarea").innerHTML = ""; }
parseAnchors();
}
window.onload = function () {
parseAnchors();
}
</script>
After several pieces of helpful advice from the members of this forum I'm getting closer to solving what should be a simple issue. I'm a complete newbie to AJAX.
Can someone please tell me why this piece of code works fine in Firefox 8 but not in IE 9? It works ONCE in IE but not again unless I close the browser and reopen!!??
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch(e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readyState == 4) {
}
}
ajaxRequest.open("GET", "disp_processTEXT.asp", false);
ajaxRequest.send(null);
}
//-->
</script>
The readystate is left blank as it is copied code which originally assigned a value to a div but I only want to run the database code in the asp page. Presumably this could have been deleted?
The code to be run in the asp page is
<%
Set MyConn = Server.CreateObject("ADODB.Connection")
MyConn.Open "dsn=xxx;uid=xxx;password=xxx;"
SQLString = "UPDATE dbo_tbl_printing_tempstore SET front_has_text1 = 'YES', front_text = 'help' WHERE id = 106567"
MyConn.Execute(SQLString)
MyConn.Close
Set MyConn = Nothing
%>
Please help me as this is driving me mad.
Many thanks
Switch to jQuery and its Ajax system as it should be cross browser compatable out the box, and saves you huge amounts of time:
Add a reference for jQuery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
and switch to its Ajax method (place below the above):
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'disp_processTEXT.asp',
success: function(response) {
alert('It worked');
}
});
});
</script>
Update:
To bind to the onblur event using jQuery try this. Remove the onblur= attribute from your current code.
$(document).ready(function() {
$('#yourinput').on('blur', function(){
$.ajax({
url: 'disp_processTEXT.asp',
success: function(response) {
alert('It worked');
}
});
});
});
Demo: http://jsfiddle.net/qmPLj/
Try this. It has worked for me across all browsers but some Opera versions.
function GetXmlHttpObject(handler)
{
var objXmlHttp=null;
if(navigator.userAgent.indexOf("MSIE")>=0)
{
var strName="Msxml2.XMLHTTP";
if(navigator.appVersion.indexOf("MSIE 5.5")>=0)
{
strName="Microsoft.XMLHTTP";
}
try
{
objXmlHttp=new ActiveXObject(strName);
objXmlHttp.onreadystatechange=handler;
return objXmlHttp;
}
catch(e)
{
alert("Error. Scripting for ActiveX might be disabled");
return;
}
}
else //All other browsers
{
objXmlHttp=new XMLHttpRequest();
objXmlHttp.onload=handler;
objXmlHttp.onerror=handler;
return objXmlHttp;
}
}
var url= "http://www.example.com/";
xmlHttp=GetXmlHttpObject(stateChanged);
xmlHttp.open("GET", url , true);
xmlHttp.send(null);
I've been trying to make this mootools (ver: 1.2.4) Class to process my ajax requests. But my scripts only returns readystate 1. never gets to 2,3 ,or 4, the method handleHttpResponse only seems to run once. I'ves put alerts to see and I only get 1. any ideas?
var replyXML = new Class ({
/* GDW AJAX REQUEST SCRIPT */
/* By: Jonathan Robidas 2011-05-13 */
initialize : function(url){
this.http = this.getHTTPObject(); // We create the HTTP Object
this.url = url; // Requested server-side script
this.response = ''; // String returned by AJAX, Set after positive response
},
returnResponse : function() {
return this.response;
},
handleHttpResponse : function() {
alert(this.http.readyState);
if (this.http.readyState == 4) {
if(this.http.status==200) {
alert("YA YA 2");
this.response = this.http.responseText;
return true;
}
}
},
requestXML : function() {
this.http.open("GET", this.url, true);
//this.http.onreadystateshange = this.handleHttpResponse();
this.http.onload = this.handleHttpResponse();
},
getHTTPObject : function() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
});
This is how i launch it for now. my content is null but my url is a working XML file. so it shouldnt be blank... ?
<script language="Javascript" type="text/Javascript">
window.addEvent('domready', function() {
loadXML = new replyXML('gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59');
loadXML.requestXML();
content = loadXML.returnResponse();
alert(content);
/*
x=content.documentElement.childNodes;
for (i=0;i<x.length;i++) {
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}
*/
});
</script>
Tested on Google chrome, Firefox 4, Internet explorer 7 & 8, all same result.
Here is an example of XML the script is suppose to output: http://jerenovici.net/gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59 so I know my php generating the xml is fine.
Thanks!!
Why are you reinventing the wheel? If you're using mootools, making an ajax request is extremely easy (docs, referring to newest version, but in this case Request hasn't changed):
new Request({
url : './gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59',
onSuccess : function(responseText, responseXML){
/* here, do stuff with your response */
},
onFailure : function(xhr){
/* the XMLHttpRequest instance. */
}
}).send();
Then, are you sure the url is correct?