最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - trigger a javascript function before on any AJAX call - Stack Overflow

programmeradmin2浏览0评论

Here, I have a function which needs to be called before any AJAX call present in the .NET project.

Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.

In short, I want to make function behave like an event which will be triggered before any AJAX call

Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...

//check internet availability
function checkConnection() {
    //stuff here to check internet then, set return value in the variable
    return Retval;
}

//Ajax call
function SaveData() {
        var YearData = {
            "holiday_date": D.getElementById('txtYears').value
        };
        $.ajax({
            type: "POST",
            url: 'Service1.svc/SaveYears',
            data: JSON.stringify(YearData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: true,
            success: function (data, status, jqXHR) {
                //fill page data from DB
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
    }

And below is current way to call function:

<form onsubmit="return Save();">
    <input type="text" id="txtYears" /><br />
    <input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
    <script>
        function Save() {
            if (confirm('Are you sure?')) {
                SaveData();
            }
            else {
                return false;
            }
        }
    </script>
</form>

Here, I have a function which needs to be called before any AJAX call present in the .NET project.

Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.

In short, I want to make function behave like an event which will be triggered before any AJAX call

Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...

//check internet availability
function checkConnection() {
    //stuff here to check internet then, set return value in the variable
    return Retval;
}

//Ajax call
function SaveData() {
        var YearData = {
            "holiday_date": D.getElementById('txtYears').value
        };
        $.ajax({
            type: "POST",
            url: 'Service1.svc/SaveYears',
            data: JSON.stringify(YearData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: true,
            success: function (data, status, jqXHR) {
                //fill page data from DB
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
    }

And below is current way to call function:

<form onsubmit="return Save();">
    <input type="text" id="txtYears" /><br />
    <input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
    <script>
        function Save() {
            if (confirm('Are you sure?')) {
                SaveData();
            }
            else {
                return false;
            }
        }
    </script>
</form>
Share Improve this question edited Nov 9, 2016 at 6:33 Vikrant asked Apr 7, 2015 at 10:20 VikrantVikrant 5,03618 gold badges51 silver badges74 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 10

You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.

So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:

$.ajax({
            type: "POST",
            url: 'Service1.svc/SaveYears',
            data: JSON.stringify(YearData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: true,
            beforeSend: function() {
               if(!checkConnection())
                   return false;
            },
            success: function (data, status, jqXHR) {
                //fill page data from DB
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });

It reduces the call that you have made onsubmit() of form tag!

UPDATE: to register a global function before every AJAX request use:

$(document).ajaxSend(function() {
  if(!checkConnection())
     return false;
});

The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).

jQuery already supports custom publish-subsrcibe

For this specific example just do this:

//Ajax call
function SaveData(element) {
       var doAjax = true; 
       var YearData = {
            "holiday_date": D.getElementById('txtYears').value
        };
        if (element === myForm) 
        {
           doAjax = checkConnection();
        }
        if ( doAjax )
        {
        $.ajax({
            type: "POST",
            url: 'Service1.svc/SaveYears',
            data: JSON.stringify(YearData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: true,
            success: function (data, status, jqXHR) {
                //fill page data from DB
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
        }
        else
        {
          // display a message
        }
    }

Hope i understand correctly what you mean.

UPDATE:

in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))

If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well

You can use:

$(document)
.ajaxStart(function () {
  alert("ajax start");
})
.ajaxComplete(function () {
     alert("ajax complete");
})

That's it!!

use

beforeSend: function () {
},  

ajax method

发布评论

评论列表(0)

  1. 暂无评论