Fraz Sundal
Fraz Sundal

Reputation: 10448

Issue in jquery ajax on download file link

In my page i have download links to files like Documents,Audio and Video and on click of that download link i want to update hits counter in database for that i use the strategy of jquery ajax request that will update hits counter but the issue is when i click on hyperlink it call the jquery function but doesnt call my controller action and download popups appear. What may be the issue for reference im writing the code

<a att="1" href="../Abc.doc">Download</a>
<a att="2" href="../Abcs.wmv">Download</a>

and in jquery

  $('a').click(function () {
                    var myurl = '<%= Url.Action("UpdateHits", "Media") %>';
                    var id = $(this).attr('att').toString();
                    $.ajax({
                        url: myurl,
                        type: "POST",
                        data: { Id: id },
                        success: function (data) {
                            alert(data);
                        }
                    });
                });

Upvotes: 1

Views: 3133

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039110

Make sure you cancel the default action by returning false so that the browser doesn't follow the link.

$('a').click(function () {
    var myurl = '<%= Url.Action("UpdateHits", "Media") %>';
    var id = $(this).attr('att').toString();
    $.ajax({
        url: myurl,
        type: 'POST',
        data: { Id: id },
        success: function (data) {
            alert('success');
        }
    });
    return false;
});

Also instead of going through all this pain in javascript I would recommend you generating proper anchor links:

<%= Html.ActionLink("Abc.doc", "UpdateHits", "Media", new { id = 1 }, null) %>
<%= Html.ActionLink("Abcs.wmv", "UpdateHits", "Media", new { id = 2 }, null) %>

And simply ajaxify them:

$(function() {
    $('a').click(function() {
        $.post(this.href, function(data) {
            alert('success');
        });
        return false;
    });
});

Upvotes: 2

Liam Bailey
Liam Bailey

Reputation: 5905

You need:

     $('a').click(function (e) {
    e.preventDefault();
                        var myurl = '<%= Url.Action("UpdateHits", "Media") %>';
                        var id = $(this).attr('att').toString();
                        $.ajax({
                            url: myurl,
                            type: "POST",
                            data: { Id: id },
                            success: function (data) {
                                alert(data);
                            }
                        });
return true;
                    });

Prevent default stops the link from being followed until the js is through doing what it needs to, throw in the return truie to let it continue with the link follow.

Upvotes: 0

Related Questions