Combine JQuery/PHP to log clicks into database?

Go To


enter image description here

The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.

I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.

Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.

How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?

Below is the JQuery function.

$(document).ready(function() { 
    $('.accordionButton').click(function(e) {
        if($(this).next().is(':hidden') == true) {
            alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
         else {
2012-04-03 20:42
by Jon
If you have budget and prefer to not reinvent the wheel, I'd recommend - AlienWebguy 2012-04-03 20:44
Interesting. I'd rather just build it myself. I have a database set up and a learning algorithm in place already, so all I need to do is figure out some way to see what the user is clicking on. Thank you for the suggestion, though - Jon 2012-04-03 20:46
Use AJAX!! - Ben Carey 2012-04-03 20:50
I'm new to dynamic web programming, so I wasn't really familiar with all of the capabilities of AJAX. I kinda figured it was something simple like that. Thanks, guys! Pardon my ignorance - Jon 2012-04-03 20:53
Yes, as Ben Carey said, use ajax to get your php script. You can use a GET variable to, so you can log clicks. Simply let the script open counter.php?word=hello and in that script do the query. The user won't notice a thing - ArendE 2012-04-03 20:53
@Jon +1 for being so friendly :- - Ben Carey 2012-04-03 21:03


You can do something like this (untested):

Define a javascript variable to track the order of the clicks, outside your click function:

var order = 0;

Add this into your click function, at the bottom:

var sessionID = $("input[name='sessionID']").val();  // assuming you have sessionID as the value of a hidden input
var query = $("#query").text();    // if 'query' is the id of your searchbox
var pos = $(this).index() + 1;     // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});

In your php script called "logClick.php" (in the same directory):

    $str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
    $str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
    $int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
    $int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];

    if ($str_sessionID && $str_query) {
        require_once "dbconnect.php";    // include the commands used to connect to your database. Should define a variable $con as the mysql connection

        $sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
        $res = mysql_query($sql_query, $con);
        if (!$res) die('Could not connect: ' . mysql_error());
        else echo "Click was logged.";
    else echo "No data found to log!";

You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:

$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
    function(result) {
      $('#result').html(result);  // display script output into a div with id='result'
      // or just alert(result);

EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).

Example (put this in every results page):

   $order = empty($_POST["order"]) ? $_POST["order"] : "0";
   $html="<form id='form_session' action='' name='form_session' method='POST'>
        <input type='hidden' name='order' value='$order'>
   echo $html;

In your jQuery, just change var order = 0; to

var order = $("input[name='order']").val();

Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:

$("a.next_page").click(function(event) {
  var url = $(this).attr("href");
  $("#form_session").attr('action', url).submit();

All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).

EDIT: If your pagination is as follows:

<div class='pagination'>
    <ul><li><a href='page1.url'>1</a></li>
        <li><a href='page2.url'>2</a></li>

then just change this:

$("div.pagination a").click(function(event) {
2012-04-03 21:30
by Stefan
This worked perfectly, but the only thing wrong still is the order variable. Since the results are paginated, I want to keep the click order active until they initiate a new search. So somehow I need to globally store the "order" count, but I'm not sure how. Any ideas - Jon 2012-04-04 17:01
@Jon: The order variable in my code above is meant to be global. I think it just needs to be reset when a new query is submitted by the user. In other words you just need to catch the 'click' event for the searchbox submit button, or catch when 'Enter' is pressed, and then reset this variable outside of your accordionButton's click method, for example $(document).keypress(function(e) {if(e.keyCode == 13) order = 0;});Stefan 2012-04-04 17:26
@Jon: You mean, when they load a new page with results, the page is reloaded? Yes, then the order value as used above is lost. Solutions: 1. Either use jQuery and just load a div with the new results instead or loading a new page. 2. You can pass the order variable via a GET parameter in the new page url, then either read it's value directly with javascript, or store it's value in a hidden input using php, and read it from there with jQuery - Stefan 2012-04-04 17:32
@Jon: I updated my answer with some suggestions. You can also use cookies, if you like. Also remember to test for javascript and to warn your users that it must be enabled if it is not - Stefan 2012-04-04 18:44
Is a.next_page the ID of the hyperlink for the "Next" and "Prev" buttons in the pagination - Jon 2012-04-04 19:11
@Jon: No, it's the class of all those links: <a href='' class='next_page' title='Page 2'>2</a><a href='' class='next_page' title='Page 3'>3</a>Stefan 2012-04-04 19:13
My pagination is set up as follows: ... I'm still confused though what a.next_page represents - Jon 2012-04-04 19:27
@Jon: the jQuery selector `a.nextpage' means "all anchors with class='nextpage'". But I have modified my code to use your pagination structure - Stefan 2012-04-04 19:34
let us continue this discussion in chatJon 2012-04-04 19:35


Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):

In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:

Something like:

  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston"
  success: function(data){
2012-04-03 20:51
by Ben Carey
Perfect! This makes a lot of sense. Thank you - Jon 2012-04-03 21:18


This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.

In your search page you'll need to add an .ajax to create an AJAX request to your Script. Everything you need to know about AJAX can be found here:

In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.

2012-04-03 20:52
by peipst9lker


Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.

A little example, on click:

{ id: "someid" },
function(data) {
// data = everything the php-script prints out


if (isset($_POST['id'])) {
// add a click in the database with this id
2012-04-03 20:55
by Sander Bruggeman