0

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?

Rodrigo Lessa
  • 69
  • 3
  • 11
  • 1
    What you are trying to do is for one user only , so basically you need to use database to store clicks ,this can be done using ajax and php – Charaf JRA Aug 28 '13 at 04:51
  • 1
    Have you tried something to implement your idea other than just posting it here? – Muhammad Talha Akbar Aug 28 '13 at 04:51
  • @muhammad talha akbar yea ive created a database and im trying to make the number increment by 1 everytime a link is clicked but im failing – Rodrigo Lessa Aug 28 '13 at 04:53
  • you want click on 10 20 30 th or 10 11 12th and so on.. – xkeshav Aug 28 '13 at 04:54
  • 1
    possible duplicate of [changing a link href after total number it is clicked on](http://stackoverflow.com/questions/18479285/changing-a-link-href-after-total-number-it-is-clicked-on) – Arun P Johny Aug 28 '13 at 04:54
  • 1
    this site is for help, you are not providing a problem, you could of easily googled "get link click count php" – Young Student Aug 28 '13 at 04:57

6 Answers6

2

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.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • thanks that pretty much what i was asking im tyring to look on google for some explanation in how to do this process but cant seem to find any new information everything is from 2003-2008 do u have any articles or forums that would help me with this? – Rodrigo Lessa Aug 28 '13 at 05:31
1

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

Manu M
  • 1,074
  • 5
  • 17
1

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']);
    }
}
Parfait
  • 1,752
  • 1
  • 11
  • 12
  • It seems that in javascript are syntax errors –  Jan 24 '21 at 10:47
  • In the JS file, add **);** just after the last curly bracket; it is missing in the code. Also, **,** is needed after data field as **data: {id:ref},** The owner needs to edit this. – Ajowi Jun 02 '22 at 11:05
0
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

Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
0

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

xkeshav
  • 53,360
  • 44
  • 177
  • 245
0

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.

Harish Ambady
  • 12,525
  • 4
  • 29
  • 54