Skip to content

Instantly share code, notes, and snippets.

@jpalala
Created October 1, 2024 01:27
Show Gist options
  • Save jpalala/148c206032806b00b54c8a706c96bc27 to your computer and use it in GitHub Desktop.
Save jpalala/148c206032806b00b54c8a706c96bc27 to your computer and use it in GitHub Desktop.
how to track unique clicks using jquery

Note: From ChatGPT. Thank you ChatGPT!

To implement click tracking with jQuery and store it in a backend API, we can outline the following steps:

1. Database Schema

You can use a database table to store unique clicks, capturing the necessary details like the browser, IP address, and clicked_at timestamp.

SQL for the table:

CREATE TABLE unique_clicks (
    id INT AUTO_INCREMENT PRIMARY KEY,
    browser VARCHAR(255),
    ip_address VARCHAR(45),  -- To accommodate both IPv4 and IPv6 addresses
    clicked_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(ip_address)  -- Ensures only one record per IP address
);

This schema ensures that each ip_address is stored only once due to the UNIQUE constraint on the ip_address column. The browser field will store details about the browser used during the click.

2. Backend API (Example using PHP & Laravel)

Create a simple API endpoint to handle the POST request from jQuery. Here is an example of how it could be done using Laravel:

// routes/api.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

Route::post('/track-click', function (Request $request) {
    $ip = $request->ip();
    $browser = $request->header('User-Agent');

    try {
        DB::table('unique_clicks')->insert([
            'ip_address' => $ip,
            'browser' => $browser
        ]);
    } catch (\Illuminate\Database\QueryException $e) {
        // Handle duplicate IPs or other errors
        return response()->json(['message' => 'Duplicate IP or error occurred'], 409);
    }

    return response()->json(['message' => 'Click recorded'], 201);
});

This will save the unique IP address and browser details when the click event is triggered.

3. Frontend jQuery to Capture Clicks

You can use the following jQuery code to capture clicks on specific elements and send the data to your backend API.

$(document).ready(function() {
    $('body').on('click', function(e) {
        $.ajax({
            url: '/api/track-click',
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')  // For Laravel CSRF protection
            },
            success: function(response) {
                console.log('Click recorded successfully');
            },
            error: function(xhr) {
                console.error('Error recording click:', xhr.responseText);
            }
        });
    });
});

This script will listen for click events on the page and send a request to your backend, along with the IP address (handled by Laravel's Request::ip() method) and browser information (passed via the User-Agent header).

4. Additional Considerations

  • CSRF Protection: Ensure that the X-CSRF-TOKEN is included in the request headers if you're using Laravel with CSRF protection enabled.
  • Performance: If you have a high volume of traffic, you might want to batch inserts or use a caching mechanism to reduce database writes.
  • Rate Limiting: Consider implementing rate limiting to avoid abuse of the API by too many requests from the same IP.

This setup allows you to track clicks on your page and record only unique IP addresses, capturing the browser details as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment