Ajax Listener - how does it work?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Ajax Listener - how does it work?

Post by simonmlewis »

I have a tool on a site where they click a button to add a sample to a cart. It pops it into a databse with a session ID.

In the top menu it says "order samples", and if the page turns over, it then queries what's in the cart for them. But it would be really cool if after they clicked Continue Shopping on the popup, via ajax, the digit of (1) or (2) or whatever is added, just magically appeared.

Even better would be if it could do it with some kind of "flicker" to highlight the fact that it's "updated".

How does these kinds of things work?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Ajax Listener - how does it work?

Post by Celauran »

What does your AJAX request return? Could you not use that to update the item count?
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Ajax Listener - how does it work?

Post by simonmlewis »

It doesn't return. It sends data to an external PHP file.
Then the continue shopping button that is like a light box just closes that box nothing changes in the page.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Ajax Listener - how does it work?

Post by Celauran »

Well there's your solution, then. Have the PHP script return the number of items in the cart and use that to update the display.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Ajax Listener - how does it work?

Post by simonmlewis »

But the PHP script will do that when the page "turns over". When they click the button it doesn't turn over. It's just like closing a lightbox.

So I either have the "continue shopping" link turn the page over (not a fan of that), or something that listens and updates the amount from the database.

IE. if it shows (1), and you click button to add, the database via Ajax as 2. But since the page hasn't refreshed, (1) still shows.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Ajax Listener - how does it work?

Post by Celauran »

simonmlewis wrote:But since the page hasn't refreshed, (1) still shows.
No. That's the whole point of using AJAX; you can update asynchronously. Have the PHP script that updates the cart return the number of items now in the user's cart, catch that in the success callback, and update your display.

http://api.jquery.com/jQuery.ajax/
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Ajax Listener - how does it work?

Post by simonmlewis »

But how does my small bit of PHP in the top that asks for a count of how many are in the database cart, asking AGAIN... without the page reloading?

When I click the button to add, a popup appears on darkened screen, which doesn't really 'do' anything, it's just a confirmation.
The separate *.php file is what adds it to the cart db table.

So what do I need to put into my query to keep it "checking" the database table?

Code: Select all

if(isset($sessionid))
{
$resultcheck = mysql_query ("SELECT id FROM samples WHERE userid = '$sessionid' AND status = 'added'");
  $num_sample = mysql_num_rows($resultcheck); 
  if ($num_sample != 0) { echo " ($num_sample)";}
}

if(isset($userid))
{
$resultcheck = mysql_query ("SELECT id FROM samples WHERE userid = '$userid' AND status = 'added'");
  $num_sample = mysql_num_rows($resultcheck); 
  if ($num_sample != 0) { echo " ($num_sample)";}
}
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Ajax Listener - how does it work?

Post by Celauran »

simonmlewis wrote:But how does my small bit of PHP in the top that asks for a count of how many are in the database cart, asking AGAIN... without the page reloading?
It doesn't.
simonmlewis wrote:The separate *.php file is what adds it to the cart db table.
This one does. This receives the AJAX request, updates the DB, and can then get the count and return it.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Ajax Listener - how does it work?

Post by simonmlewis »

Fine. But the page at the top has already loaded. It's not loading a second time after I've added to cart.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Ajax Listener - how does it work?

Post by Celauran »

Nor does it need to. Once you get the new count back, use jQuery to update the DOM.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Ajax Listener - how does it work?

Post by simonmlewis »

use jQuery to update the DOM.
This is the bit I don't understand and need to learn.
I've never done that. So how does that keep looking at it, or does it learn that I have jsut done something?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Ajax Listener - how does it work?

Post by Celauran »

Contrived example, but assume shopping cart markup like this. Yes, yours is likely more detailed, has a trolley icon, etc. Doesn't matter.

Code: Select all

<div id="shopping_cart">
	<span class="count">2</span>
</div>
You have your event listener attached to your "Add item to cart" buttons. Have the script that updates the DB also return the count of items in the user's cart. The success callback can then use that return value to update the markup above.

Code: Select all

$('.add_to_cart').click(function() {
	// Collect data
	$.ajax({
		url: "some_file.php",
		type: "POST",
		data: whatever,
		success: function(data, status, request) {
			var cart_count = data;
			$('#shopping_cart .count').html(cart_count);
		}
	});
});
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Ajax Listener - how does it work?

Post by simonmlewis »

So it goes in here somewhere, which is the separate PHP file?

Code: Select all

<?php
session_start();
$today = date('Y-m-d');

		if (isset($_SESSION["loggedin"])) 
            {
            $userid = $_SESSION["userid"];
            }
            
$sessionid = isset($_SESSION['sessionid']) ? $_SESSION['sessionid'] : null;
$prodid = isset($_GET['q']) ? $_GET['q'] : null;

if(!isset($userid) && !isset($sessionid))
  {
  $random = (rand()%99999999);
  $_SESSION['sessionid'] = $random;
  $sessionid = $_SESSION['sessionid'];
  }
	include "dbconn.php";
	
	$result = mysql_query ("SELECT id, title FROM products WHERE id = '$prodid'");
while ($row = mysql_fetch_object($result))
      {

$prodname = $row->title;
}

if (isset($userid))
  {
  $resultcheck = mysql_query ("SELECT id FROM samples WHERE userid = '$userid' AND status = 'added'");
  }
  else
  {
  $resultcheck = mysql_query ("SELECT id FROM samples WHERE userid = '$sessionid' AND status = 'added'");
  }
  $num_disable = mysql_num_rows($resultcheck); 
  if ($num_disable == "6") { $disable = "yes";
  }
    else
    {
    $disable = NULL;
    if (isset($userid))
      {
      $resultcheck = mysql_query ("SELECT id FROM samples WHERE prodid = '$prodid' AND userid = '$userid' AND status = 'added'");
      }
    else
      {
      $resultcheck = mysql_query ("SELECT id FROM samples WHERE prodid = '$prodid' AND userid = '$sessionid' AND status = 'added'");
      }
  
    $num_sample = mysql_num_rows($resultcheck); 
    if ($num_sample == 0)
      {
      if (isset($userid))
        {
        mysql_query("INSERT INTO samples (userid, prodid, prodname, dateadded, status) VALUES ('$userid', '$prodid', '$prodname', '$today', 'added')");
        }
        else
        {
        mysql_query("INSERT INTO samples (userid, prodid, prodname, dateadded, status) VALUES ('$sessionid', '$prodid', '$prodname', '$today', 'added')");
        }
      }
      }
      

?>
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Ajax Listener - how does it work?

Post by Celauran »

Yeah, that should work. Once you've processed the incoming request, get the count, echo it, and your jQuery event listener can handle updating the HTML.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Ajax Listener - how does it work?

Post by simonmlewis »

Sorry I am still not with this.

Code: Select all

function precheck(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
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("srcHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","/ajax_addtocart.php?q="+str,true);
xmlhttp.send();
}
This is the script that sends the info to ajax_addtocart.php.

Where should that listener bit go?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
Post Reply