Kiran
Kiran

Reputation: 41

Common beforeSend in Ajax call and abort if conditions not satisfied

I am trying to write a common functionality to all Ajax call as below. The abort is not working when I write it separately like below,it works if I add the beforesend in the same ajax as below, which is commented

 $(document).ready(function () {

                        $.ajax({
                            beforeSend: function (jqXHR, settings) {
                                check = TestCallMethod();
                                if (check.responseText != "true") {
                                    alert("Call Failed");
                                    jqXHR.abort(event);
                                }
                            }
                        });

            $.ajax({
//                beforeSend: function (jqXHR, settings) {
//                    debugger;
//                    check = TestCallMethod();
//                    if (check.responseText != "true") {
//                        alert("Call Failed");
//                        jqXHR.abort();
//                    }
//                },
                cache: false,
                url: '@Url.Action("TestCall2", "Home")',
                success: function (data) {
                    alert(data);
                },
                error: function (request, status, error) {
                    alert(request.responseText);
                }
            });
        });

        function TestCallMethod()
        {
            return  $.ajax({
                url: '@Url.Action("TestCall", "Home")',
                async: false,
                cache: false,
                success: function (data) {
                    return data;
                },
                error: function (request, status, error) {
                    alert(request.responseText);
                    return false;
                }

            });
        } 

How to achieve the abort for common ajax beforsend?

Upvotes: 2

Views: 1392

Answers (1)

surendersingh.it
surendersingh.it

Reputation: 11

You can apply common settings to global on Ajax . I hope it would be helpful.

$.ajaxSetup({
    global: true,
    beforeSend: function (jqXHR, settings) {
        check = TestCallMethod();
            if (check.responseText != "true") {
                alert("Call Failed");
                jqXHR.abort(event);
            }
    }
});

Upvotes: 1

Related Questions