How to prevent anchor tag request on ajax response?

Total Post:113

Points:791
Mvc 
C#
 559  View(s)
Ratings:
Rate this:

Hi,

I want to stop anchor tag request on ajax response.

Here is my code:

<a class="anchorTag" href="@Url.Action("ActionName", "ControllerName")" >Click Here...</a>
<script>
$(function () {
    $('.anchorTag').click(function (e) {
     var data = {
            postID: 001
        };
        $.ajax({
            type: "POST",
            url: "../../ControllerName/ActionName",
            data: JSON.stringify(data),
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                if (response.success == true) {  
                }
                else {  
                }
            }
        });
    });
});
</script>

Please give me some solution to achieve this task.

  1. Post:44

    Points:310
    Re: How to prevent anchor tag request on ajax response?

    Hi Franco, 

    I analyzed your code. You can achieve your task by using object.preventDefault().

    But used this method carefully.

    Your modified code is as follows:

    <script>
    
    $(function () {

        $('.anchorTag').click(function (e) {
            e.preventDefault();
            var me = this;

            var data = {
                postID: 001
            };

            $.ajax({
                type: "POST",
                url: "../../ControllerName/ActionName",
                data: JSON.stringify(data),
                dataType: "json",
                contentType: 'application/json; charset=utf-8',
                success: function (response) {
                    if (response.success == true) {
                        window.location = $(me).attr("href");
                    }
                    else {

                    }
                }
            });

        });
    });
    </script>

    I hope it's informative!!!

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!