Jump to content

Recommended Posts

I am developing an ajax application using css tabs.

Each tab has content dynamically updated by ajax from php scripts.

The problem comes from one such php script, It is a simple hyperlink line of code such as the following :
echo "<a href=\"www.google.com\">Google</a>";

does not work in Internet explorer but worrks perfectly in Firefox. A javascript error comes up in explorer saying:
"unknown runtime error".

I thought I found a solution when I read somewhere about taking out spaces.
So I encoded the space after '<a' in the following way:
echo "<a%20href=\"www.google.com\"> Google </a>";

In IE, instead of the error, the 'www.google.com' text was displayed but it was not hyperlinked.
And in Firefoxm, the text was displayed but it wasn't hyperlinked either.

???
Can someone please help me,
Sazzie.
Link to comment
https://forums.phpfreaks.com/topic/32711-ie-vs-firefox-showdown/
Share on other sites

I have put the code you requested I hope you can make sense of it. I also included a section of code from
a larger but seperated php script which handles the tabs and points the selected tab at simple.php(next)

My simple.php script:

<?php

echo "<a href=\"www.google.com\">Google</a>";
?>

*******************************************************************

//my not so simple javascript

var request = null;
var userID = "ucyzrka";
var div_handler = new handleDivTag(null);
var page_url = null;

createRequest();

function createRequest()
{
try{
request = new XMLHttpRequest(); //non microsoft
}catch( trymicrosoft )
{
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
}catch( othermicrosoft )
{
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}catch( failed )
{
request = null;
}
}
}

if( request == null )
alert("Error Creating XMLHttpRequest!");
}

function div_manager( divTag, url )
{
div_handler.divTag =  divTag;
page_url = url;

access_private();
}

function tab_manager( divTag, url, id )//div to load content to, the url of the source file and the ID of the html tag
{
div_handler.divTag =  divTag;
// page_url = encodeURI(url);
page_url = url;

// document.write(page_url);
// alert(page_url);

elList = document.getElementsByTagName("li");

//this section of code sets the active tabs and unsets the inactive tab
for (i = 0; i < elList.length; i++)
{
    // Check if the link's target matches the frame being loaded.
if( elList[i].id == id )
{
if( !attributeCheck(elList[i],'active') )
{
elList[i].className += " active";
}
}
else if( (elList[i].id).match("tab-header") )
{
if( attributeCheck(elList[i],'active') )
{
removeName( elList[i], " active" );
}
}
}

access_private();
}

function collect()
{
if( request.readyState == 4 )
{
if( request.status == 200 )
{
var text = request.responseText;

document.getElementById(div_handler.divTag).innerHTML = text; //[color=red][font=Verdana][u]<--- IE error is with this line[/u][/font][/color]
}
else
{
alert("WARNING! : Request Object Status Is Invalid!");
}
}
}

function access_private()
{
// alert("In access_private : "+page_url);
// request.open("GET", page_url+"?login="+userID, true);
request.open("GET", page_url, true);
request.onreadystatechange = collect;
request.send(null);
}

function handleDivTag( divTag )
{
var divTag;
return divTag;
}

function attributeCheck( el, attrib )
{
var i, curList, newList;
  // Remove the given class name from the element's className property.
newList = new Array();
curList = el.className.split(" ");

for (i = 0; i < curList.length; i++)
if (curList[i] == attrib)
return true;
return false;
}

// scripting for tabbing effects.
function removeName(el, name)
{
var i, curList, newList;
  // Remove the given class name from the element's className property.
newList = new Array();
curList = el.className.split(" ");

for (i = 1; i < curList.length; i++) //starting count from 1 'cuz at 0, curList.lenght is 1 with empty for value
{
if( curList[i].match(name) ) //matching active against the current list on class element
newList.push(curList[i]);
}

el.className = newList.join(" ");
}

**********************************************************************************
.
.
.
function tabs()
{
echo "<ul class=\"tab-headers\">";
echo "<li id=\"tab-header1\" class=\"active\"> <a href=\"javascript:void(0);\" id=\"id_tab1\" onClick=\"tab_manager('tab-content1','private/courses/Welcome.php', 'tab-header1');\"> Welcome </li>";
echo "<li id=\"tab-header2\" class=\"\"> <a href=\"javascript:void(0);\" id=\"id_tab2\" onClick=\"tab_manager('tab-content1','private/courses/View_All.php', 'tab-header2');\"> View All Courses </li>";
echo "<li id=\"tab-header3\" class=\"\"> <a href=\"javascript:void(0);\" id=\"id_tab3\" onClick=\"tab_manager('tab-content1','private/courses/View_Current.php', 'tab-header3');\"> View '07 Courses </li>";
echo "<li id=\"tab-header4\" class=\"\"> <a href=\"javascript:void(0);\" id=\"id_tab4\" onClick=\"tab_manager('tab-content1','private/courses/simple.php', 'tab-header4');\"> Add Courses </li>";
echo "</ul>";
echo "<div id=\"container\">";
echo "<div class=\"tab-content\" id=\"tab-content1\"></div>";
echo "</div>";
}
.
.
.
Apparently, js allows you to create objects of functions. So the following is the defining function :

[color=red]function handleDivTag( divTag )
{
var divTag;
return divTag;
}
[/color]
And the code below creates an object of that function:

[color=red]var div_handler = new handleDivTag(null);[/color]

This code works because every other aspect of my project has not issue with it in either Firefox or Explorer - except
of course in the part I described above.

So [color=red]div_handler.divTag[/color] simply uses an variable of the created object.
Ok.. well. I can get it working using XML. I think it would be a good idea in any case to use XML for such things because it's so easy to parse and work with. Example below.. I just use some small AJAX wrappers for easy access, you can use your own.

This was tested in IE 7, and echo's out (with highlighted links)

[quote]
Links should appear below, in this div..

Name: Link to google.com, link: Google - knower of all
Name: Link to phpfreaks.com, link: PHPFreaks > google
[/quote]

You can try it here: http://conventia.dk/pixels/tab.html

The files:

[b]/tab.html[/b]
[code]
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hi mom</title>
<script type="text/javascript" src="javascript/model/AjaxUpdater.js"></script>
<script type="text/javascript" src="javascript/model/Ajax.js"></script>

<script language="javascript">

TabControl = { };

TabControl.response = function()
{
    try
    {
        if (Ajax.checkReadyState('tabs') == "200")
        {
            var tabsDiv = document.getElementById("tabs");
           
            if (tabsDiv)
            {
                // Parse XML response
                var tabs = Ajax.getResponse().getElementsByTagName('tab');
           
                // Loop through amount of <tab> elements returned
                for (var i = 0; i < tabs.length; i++)
                {
                    // Get element <name>
                    var tabName = Ajax.getResponse().getElementsByTagName('name')[i].firstChild.data;
                    // Get element <link>
                    var tabLink = Ajax.getResponse().getElementsByTagName('link')[i].firstChild.data;
           
                    // Magic!
                    tabsDiv.innerHTML += "Name: " + tabName + ", link: " + tabLink + "<br />";
                }
            }
            else
            {
                alert("Hey.. something's wrong!");
            }
        } // if (Ajax.checkReadyState('tabs') == "200")
    }
    catch (err)
    {
        alert("Exception: " + err);
    }
}
</script>
</head>
<body onload="javascript:AjaxUpdater.Update('POST', 'classes/simple.php', TabControl.response);">
<div id="tabs">
    <p>Links should appear below, in this div..</p>
</div>
</body>
</html>
[/code]

[b]classes/simple.php[/b] - notice how the HTML data is placed between CDATA tags.
[code]
<?php

    $xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
    $xml .= "<tabs>\n";
    $xml .= "<tab>\n";
    $xml .= "<name>Link to google.com</name>\n";
    $xml .= "<link><![CDATA[<a href=\"http://www.google.com/\">Google - knower of all</a>]]></link>\n";
    $xml .= "</tab>\n";
    $xml .= "<tab>\n";
    $xml .= "<name>Link to phpfreaks.com</name>\n";
    $xml .= "<link><![CDATA[<a href=\"http://www.phpfreaks.com/\">PHPFreaks > google</a>]]></link>\n";
    $xml .= "</tab>\n";   
    $xml .= "</tabs>";
   
    // Set header type so AJAX knows that it's an XML object
    header("Content-Type: application/xml; charset=UTF-8");
    echo $xml;

?>
[/code]

[b]javascript/model/Ajax.js[/b]
[code]
// JScript File

Ajax = { };

/*
* Sends an HTTP request to the server and receives a response.
*/
Ajax.makeRequest = function(method, url, callbackMethod)
{
this.request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

if (this.request)
{
   this.request.onreadystatechange = callbackMethod;
   this.request.open(method, url, true);
   this.request.send(url);
}
}

/*
* Retrieves the current state of the request operation.
*/
Ajax.checkReadyState = function(id)
{
    /*
     * 0  - Uninitialized
     * 1  - Open
     * 2  - Sent
     * 3  - Receiving
     * 4  - Loaded
     */
   
switch (this.request.readyState)
{
case 1:
break;

case 2:
break;

case 3:
break;

case 4:
AjaxUpdater.isUpdating = false;
return this.request.status;

default:
// An unexpected error has occurred
}
}

/*
* Retrieves the response body.
*/
Ajax.getResponse = function()
{
    if (this.request.getResponseHeader('Content-Type').indexOf('xml') != -1)
{
return this.request.responseXML.documentElement;
}
else
{
return this.request.responseText;
}
}
[/code]

[b]javascript/model/AjaxUpdater.js[/b]
[code]
AjaxUpdater = {};

/*
* Initialize.
*/
AjaxUpdater.initialize = function()
{
    AjaxUpdater.isUpdating = false;
}

// Initialize the class
AjaxUpdater.initialize();

/*
* Sends an HTTP request to the server and receives a response.
*/
AjaxUpdater.Update = function(method, service, callback)
{
if (callback == undefined || callback == "")
{
callback = AjaxUpdater.onResponse;
}

Ajax.makeRequest(method, service, callback);
AjaxUpdater.isUpdating = true;
}

/*
* Default event handler for asynchronous requests.
*/
AjaxUpdater.onResponse = function()
{
if (Ajax.checkReadyState('loading') == "OK")
{
AjaxUpdater.isUpdating = false;
}
}
[/code]
Another thing.. depending on how you're going to add new tabs, you should consider just using an XML file stored on the server to retrieve these tabs. It's the same procedure using AJAX. There's no reason to have a PHP script echo it out, if there's no database connection or anything that needs to be set/calculated/whatever.

Really nothing more to it than changing the url parameter of AjaxUpdater.Update somefile.xml and create said file.

Test version here (XML file): http://conventia.dk/pixels/tab_xml.html

[code]
AjaxUpdater.Update('POST', 'services/tabs.xml', TabControl.response);
[/code]

Now the code looks like:

[b]/tab_xml.html[/b]
[code]
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hi mom</title>
<script type="text/javascript" src="javascript/model/AjaxUpdater.js"></script>
<script type="text/javascript" src="javascript/model/Ajax.js"></script>

<script language="javascript">

TabControl = { };

TabControl.response = function()
{
    try
    {
        if (Ajax.checkReadyState('tabs') == "200")
        {
            var tabsDiv = document.getElementById("tabs");
           
            if (tabsDiv)
            {
                // Parse XML response
                var tabs = Ajax.getResponse().getElementsByTagName('tab');
           
                // Loop through amount of <tab> elements returned
                for (var i = 0; i < tabs.length; i++)
                {
                    // Get element <name>
                    var tabName = Ajax.getResponse().getElementsByTagName('name')[i].firstChild.data;
                    // Get element <link>
                    var tabLink = Ajax.getResponse().getElementsByTagName('link')[i].firstChild.data;
           
                    // Magic!
                    tabsDiv.innerHTML += "Name: " + tabName + ", link: " + tabLink + "<br />";
                }
            }
            else
            {
                alert("Hey.. something's wrong!");
            }
        } // if (Ajax.checkReadyState('tabs') == "200")
    }
    catch (err)
    {
        alert("Exception: " + err);
    }
}
</script>
</head>
<body onload="javascript:AjaxUpdater.Update('POST', 'services/tabs.xml', TabControl.response);">
<div id="tabs">
    <p>Links should appear below, in this div (retreived from /services/tabs.xml). Wonder if this workes in Firefox? :d</p>
</div>
</body>
</html>
[/code]

[b]services/tabs.xml[/b]
[code]
<?xml version="1.0" encoding="iso-8859-1"?>
<tabs>
<tab>
<name>Link to google.com</name>
<link><![CDATA[<a href="http://www.google.com/">Google - knower of all</a>]]></link>
</tab>
<tab>
<name>Link to phpfreaks.com</name>
<link><![CDATA[<a href="http://www.phpfreaks.com/">PHPFreaks > google</a>]]></link>
</tab>
</tabs>
[/code]
[quote author=sazzie link=topic=120845.msg497358#msg497358 date=1167994295]

Thanks alot for all your help. You guys are ahead of me at this. I had not tried XML as I am very new at this.

I will try it out and let you know.

I appreciate all you input  ;D
[/quote]

You're very welcome. Please let us know how it all turns out and if any further questions.

I've just started AJAX myself, about a week ago. The thing is with AJAX is that it's just so darn simple - yet very powerful. If you write your AJAX code from the beginning in a way that makes sense - there is ALOT of tutorials out there that are making no sense - you can easily extend it with new functions, like I did the TabControl class above. It also helps you debug if you run into errors because of the way the application (script?) is designed - easy access, function names that makes sense etc.

XML objects is just a nice way of structuring your data, XML files are easy to edit, they're easy to parse as Javascript already contains a parser for these - you do not have to make your own little parser to parse text strings returned from the PHP script. For some projects just using text strings is fine, and it's probably a good idea that you use them at first if you're very new to Javascript/AJAX, just to get a feel of how it all workes. But don't forget the power of XML files  :D
  • 2 weeks later...

Hi irken,

when I finally sorted out the problem as I described above, the solution did not come by using the XML data format.

I successfully implemented the XML data format only to find it gave me the same error as the text format.

But by accident, I found out the my hyper links worked on a different div. The section where it didn't work
had 2 or 3 divs nested into each other. I really don't know if it was the nesting which created the problem or not - I kind of suspect not.

I reduced the whole div arrangement and that part of the system now works - with responseText.  ???

Thanks for all your help. :)
Great, glad to hear it.

Debugging Javascript can be such a pain.. I still don't understand why the error handling is set up like it is. 90% - no kidding - of the error messages and explanations I get make no sense to me at all.

"null is null or not an object.. <some line that doesn't exist in my main file> + showing wrong or no file path" - wonderful :D.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.