Rodrigo Lessa
Rodrigo Lessa

Reputation: 59

Counting clicks changing link href

I asked this question but did not explain it thoroughly. I have a regular link:

<a href="http://www.google.com">Click Me</a>

I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:

var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});

I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?

Upvotes: 0

Views: 7972

Answers (6)

Harish Ambady
Harish Ambady

Reputation: 13121

You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.

<a href="http://www.google.com" class="mylink">Click Me</a>

write this javascript in the page wher you place your link

 $(function()
    {
        $('.mylink').click(function()
        {
            $.ajax({
                    type: "POST",
                    url: "listening/end/point", // enter your counting url here
                    async: false
                );

        });
    });

And in server on the listening end point write php script to store no of times that link has been called.

Upvotes: 0

Parfait
Parfait

Reputation: 1750

HTML

<a href='http://www.google.com' data-ref='99'>Click Me</a>

Javascript

$("a").click(function() {
    var _this = $(this);
    var ref = $(this).data('ref');
    $.ajax({
        url: '/click_url.php',
        type: 'POST',
        data: {id:ref}
        success: function(href) { 
            if(href != '')
               _this.attr("href",href);
        }
    });
}

PHP (click_url.php)

if($_POST['id'] > 0){
    $id = $_POST['id'];

    //count increment
    $sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
    mysql_query($sql);

    //get row count
    $sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);

    //if count > 10 , return new url
    if($row['count'] > 10){
        die($row['href']);
    }
}

Upvotes: 1

xkeshav
xkeshav

Reputation: 54016

Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9

I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click

var c=0;
$(document).on('click', 'a#ten', function(e){
    c++;
    alert('clicked ' + c + ' times');
    if(c%3 == 0) {
         $('a').attr("href","https://www.yahoo.com");
         alert('changed');
         c = 0;
    }
    e.preventDefault();
})

working DEMO

Upvotes: 0

mpen
mpen

Reputation: 282805

You have a huge fundamental misunderstanding of how JavaScript works.

Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.

Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.

So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.

We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.

Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).

Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.

Upvotes: 2

Rituraj ratan
Rituraj ratan

Reputation: 10378

var count = 0;
$(document).ready(function(){
$('a').click(function(e){

e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});

and use ajax like below

//send set state request

  $.ajax({
        type: "POST",
        contentType: "text/xml; charset=utf-8",
        datatype: "xml",// you can set json and etc
        url:"your php file url",
        data: {test:test1},// your data which you want to get and post 
        beforeSend: function (XMLHttpRequest) {
// your action 
       },
        success: function (data, textStatus, XmlHttpRequest) {
// your action        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });

for more deatils see Ajax

Upvotes: 0

Manu M
Manu M

Reputation: 1064

While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps

Upvotes: 1

Related Questions