Alright ran into a bit of a problem on the item count in my index... let me give you the layout I'm working with.

I've got my index page with the header logo and navigation bar. This is followed by an Iframe. When I click the navigation buttons it changes to Iframe to show a new webpage.

The problem I'm having is, I have a <td> in the top part of the Index (page never changes) that has a text element inside of it that calls a PHP function to show the number of items I have in the cart. So I have to reload the main page, which reloads everything back to the start in order to see the number of items.

This is the function is case you were wondering

function total_items(){
  global $sid;
  if($_SESSION["loggedin"]==1){
    $q1=mysql_query("SELECT SUM(qty) as total_items FROM cart_items WHERE uid='{$_SESSION["user_id"]}'");
  }else{
    $q1=mysql_query("SELECT SUM(qty) as total_items FROM cart_items WHERE session='$sid'");
  }
  $r1=mysql_fetch_array($q1);
  return $r1["total_items"];
}

and this is how I call it in just the text area:

<td><font color="#000000">(<?= total_items(); ?> items)</font></td>

my friend had mentioned something about AJAX, but I'm not too familiar with the blending of fields.

I appreciate any info I can get, even if its just a link to something to look up.

Recommended Answers

All 9 Replies

I got started with AJAX a couple of months ago and I love it.. There are few websites out there that have good tutorials, however, I have been using the same script for awhile, maybe this will help you get a feel for AJAX and say no more iframes!

There are three elements to my AJAX script

1. The main page, or page you are displaying
2. a javascript page, which is called into the main page
3. the results php page, which will display in a div on the main page right before your eyes

main page (hello_world.php)

<script language="JavaScript" src="world.js"></script>
<?php
//php code here 
$variable_from_page = "just an example variable";
?>

<div id="div_world"></div><br>
<a href="#" onclick="world('<? echo "$variable_from_page"; ?>');">Click for AJAX</a>

Javascript page (world.js)

var xmlHttp
function world(variable_from_form)
{ 
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="world.php"
//this passes the variable to world.php via get variable, you can add as many as you want
url=url+"?variable_from_form="+variable_from_form+"&"
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("div_world").innerHTML=xmlHttp.responseText 
 } 
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

And finally the page that will display in the div (world.php)

<?php
$variable = $_GET['variable_from_form'];
//even though we have the variable from form I will output hello
//I just brought this variable along to show how to get it from the main page to the div
echo "Hello World";
//you can exicute any code here and it will output in the div where world went
?>

interesting... it seems this may be easier than I tlhought.

Thanks alot for the info, greatly appreciated.

I'll play around with it a bit and see what I can't get working.

heh, not as easy as I thought...

After toying with this for some time, what I've managed to do is make the small area change from the original text "(# items)" into a table the same size as the area before (turns it from words to a blanks spot). This at least accomplishs the task of only changing the one area instead of the entire site.

I'm not familiar enough with the syntax for writing javascripts or XML calls, I'm learning as I go. Maybe I messed up my echo, maybe the script itself, I'm not sure. Hopefully you can see the problem?

This is what I use on the main page holding the div (index.php):
I'm calling "total_items()" from my config.php

<script language="JavaScript" src="itemcount_revert.js"></script>
...
<? 
$cartNumbers = total_items();
?>
...
<td width="50" height="20"><div id="cart_count"><font color="#000000">(<?= $cartNumbers; ?> items)</font></div></td>
<td><a href="#" onclick="itemcount_revert(<? $cartNumbers; ?>);">Click for AJAX</a></td>

This is the .js (itemcount_revert.js):

var xmlHttp
function itemcount_revert($cartNumbers)
{ 
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="world.php"
url=url+"?$cartNumbers="+$cartNumbers+"&"
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("cart_count").innerHTML=xmlHttp.responseText 
 } 
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

and this is the site displayed inside the div (world.php)

<?
$cartFinal = $_GET['cartNumbers'];

echo ("<table height=\"20\" width=\"40\">\n");
echo ("<tr>\n");
echo ("<td>.$cartFinal\n");
echo ("</td>\n");
echo ("</tr>\n");
echo ("</table>\n");
?>

If I use "echo ("<td>.$cartFinal\n");" it comes back undefined. If I use "echo ($cartFinal);" it comes up blank.

By the way... is there any way I could possibly find a snippet to make it auto refresh every so often instead of having to submit or hit a link? (meta on the world.php maybe?, java refresh maybe?) could use a bit of help on this one too if you have the time =)

is problem solved or not

just posted that... have any ideas?

Member Avatar for langsor

Using Ajax to update one number is like killing a gnat with a sledgehammer ... unless you plan on using Ajax to update your page (cart) content as well -- in which case you might lose people who have javascript turned off in their browser.

Why don't you pass the item count value in with the iFrame document and use some javascript to update the value in the iFrame's parent document?

Something like this in the iFrame updated document would work

<head>
<script type="text/javascript">
parent.document.getElementById('item_count').firstChild.nodeValue = '12 items';
</script>
</head>

And you would have your static (parent) document with the menu bar and item count printout look like this

<body>
<a href="updated.html" target="iframe">update cart</a>
<p id="item_count">0 items</p>
<iframe name="iframe" src="default.html"></iframe>
</body>

So when you load the new document, it automatically updates your item count.

Hope this helps

No luck using the method you posted, but thanks alot for the response Langsor.

With the current setup, I can get the box text change to say "(undefined items)", but not understanding where the variable is getting lost.

This is the world.php as of now:

<?
$cartFinal = $_GET['cartNumbers'];

echo ("<font color=\"#000000\">(".$cartFinal." items)</font>");
?>

Index and itemcount_revert are the same... any ideas?

I kind of like the sledghammer approach... can use this stuff for later projects ;)

Member Avatar for langsor

I admit, it's good to learn how to use the asynchronous http objects ... I did test my approach and it does work and is very easy to implement (compared to what you're doing) so if you change your mind let me know.

I noticed in post #4 from you above

<script language="JavaScript" src="itemcount_revert.js"></script>
...
<? 
$cartNumbers = total_items();
?>
...
<td width="50" height="20"><div id="cart_count"><font color="#000000">(<?= $cartNumbers; ?> items)</font></div></td>
<td><a href="#" onclick="itemcount_revert(<? $cartNumbers; ?>);">Click for AJAX</a></td>

Is the = total_items() a PHP function you're calling, or is it supposed to be a JavaScript function? Because if it's supposed to be JavaScript, you can't have PHP and JavaScript talk directly like that -- they're from opposite sides of the tracks.

<?
$cartFinal = $_GET['cartNumbers'];

echo ("<font color=\"#000000\">(".$cartFinal." items)</font>");
?>

A couple tests you can do to see where you're losing your variable data
1. give $cartFinal a static or string value to see if it echoes in your html
2. enter the page.php?cartNumbers=12 in your browser location bar to see if you're getting the $_GET query to the PHP

Are you thinking that the Ajax response will be returned as a $_GET variable, because it's returned from the xmlHttp.response type object value.

Good luck

commented: Thanks again =). +1

Sorry it took me so long to get back to you... after thinking for a while, I decided not to try and pass the variable. Instead I just put an include to my config.php(holds total_items function) on the return page (world.php) and have it refresh on an interval of 5 seconds instead of having to hit a button..

Altho I'll play with what you posted and see if I can't get it to work for me in a later project of course =).

Thanks alot for all the help from you guys. You really saved me alot of stress and confusion reading more bad tutorials and misleading forum posts. I can now say I know the basic of applying AJAX ;).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.