-1

Not after code specifically, but I need someone to point me in the right direction.

I am looking for a way to increment a MySQL value without refreshing the page immediately. I realize this may be hard to understand so I'll explain:

My index page has a series of links which each display their own lightboxes. I want to keep track of how many times each link is clicked in order to identify what users like best. Because I am using lightboxes and thus not refreshing the page when the link is clicked, I can't use google analytics or my basic skills in PHP. I don't want to refresh on click.

Should I be keeping track of each click in hidden fields on the page and then incrementing the db entries when a physical link is clicked? Is there an easier or better way to do this?

3 Answers3

1

Make an AJAX request to a PHP backend page that modifies the database for you on each click. That way, as soon as the click occurs, your database will be updated.

You didn't specify if you were using a framework, so for more information, look at this SO answer for implementations of AJAX requests in both vanilla JS as well as jQuery.

Community
  • 1
  • 1
esqew
  • 42,425
  • 27
  • 92
  • 132
0

if you keep your updated hidden and expect for a link to be clicked how would you track values when your page is closed (no click on any link)?

one way to implement your solution would be to make an async request to a separate script and pass the link-id you want it incremented.

some common javascript and a separate php (or whatever coding you want) script should do the work

0

If your lightbox is attached to anchors, as such:

<a href="img/image-1.jpg" data-lightbox="image-1" data-title="My caption">Image #1</a>

Add a class to the anchor:

<a href="img/image-1.jpg" class="mylightboxes" data-lightbox="image-1" data-title="My caption">Image #1</a>

Then, using jQuery, attach an 'onClick' event to those anchors to call your PHP script through ajax:

$('a.mylightboxes').on('click',function(){
    $.ajax({
        type:'POST',
        data:'uniquereference='+$(this).attr('data-lightbox'),
        url:'mysite/urltomyphpscript',
        success:function(){
        }
    });
    return true;
});

In your PHP script, using 'uniquereference' as a unique id to the item, increase its count in your mySQL table. I hope you can figure this part out.

This code has not been tested. Please let me know how it fares.

Mysteryos
  • 5,581
  • 2
  • 32
  • 52