Aaron Bucky
Aaron Bucky

Reputation: 21

AJAX call is not working because it proceeds to go to the link

I have a list of PDF links that is dynamically generated from the database. I want to have a log to keep track of the users who download each one.

It seems to not work because after the link is clicked, it doesn't have time to do the ajax before redirecting.

Here is the javascript:

function insertlog(linkName)
{
    $.post( "insertlog.php", { linkName: linkName, user: "<?=$username?>" } );
}

Here is the link:

 <a href="http://www.test.com/media/pdf/test.pdf" onclick="insertlog('test.pdf')">test.pdf</a>

Upvotes: 0

Views: 75

Answers (4)

Aaron Bucky
Aaron Bucky

Reputation: 21

Thank you for the help everyone. I took Nate's advice and here was the final solution:

function insertlog(linkName)
{
$.post( "insertlog.php", { linkName: linkName, user: "<?=$username?>" }, 
   function(linkName) {
        window.location = "http://www.test.com/media/pdf/"+linkName;
    });
}

and then added an echo in my insertlog.php at the end with the PDF file name.

My link looks like this:

 <a onclick="insertlog('1104.pdf')" href="#">1104.pdf</a>  

Upvotes: 0

Nate Barbettini
Nate Barbettini

Reputation: 53600

Try this:

<script>                    
function logAndGo(target)
{
    $.post( "insertlog.php", { linkName: target, user: "<?=$username?>" } )
        .then(function(url) {
            window.location = url;
        });
}
</script>

Have the server return the proper URL as a response to the log POST. Then change the link to:

<a href="#" onclick="insertlog('test.pdf')">test.pdf</a>

An even better option is what @dave proposed: create a server-side page that handles redirecting, so you can just do something like:

<a href="getFile.php?id=1234">test.pdf</a>

By handling it on the server side, you have much more control over logging, which URL to redirect to, and so on.

Upvotes: 2

void
void

Reputation: 36703

Redirect in $.post callback.

<script>                    
function logAndGo(target)
{
    $.post( "insertlog.php", { linkName: target, user: "<?=$username?>" }, fucntion(){
            window.location = 'http://www.test.com/media/pdf/' + target;
          });
}
</script>

Upvotes: 0

dave
dave

Reputation: 4104

I think the best solution to what you want to do is instead of linking to the pdf directly link to the site your ajax script calls and pass the actually requested source as a parameter.

In your script you can then do the logging and redirect to the actual source (or have the script just return the actual source).

This also allows you to track users who block Javascript. And it doesn't require two requests. And doesn't require you to maintain unnecessary Javascript code.

Upvotes: 1

Related Questions