Rami
Rami

Reputation: 8314

What is the parameter of the beforeSend jquery function?

I have been seeing some examples of the beforeSend callback function. These examples use sometimes an input parameter: beforeSend:function(req) or beforeSend:function(xhr).

I suppose that this parameter is the XMLHTTPRequest of the jquery request, but when I try these examples it seems that the xhr or the req objects are null.

Is it necessary to create the xhr parameter and initialize it before calling the execution of the jquery object?

Here is the query that I am trying:

function make_basic_auth(un, pss)
{
  var tok = un + ':' + pss;
  var hash = Base64.encode(tok);
  return "Basic " + hash;
}

$('#loginform').submit(function()
{
    $.ajax
    (
        {
            type: 'POST',
            url: 'my.ip.address',
            beforeSend: function(jqXHR, settings)
            {   
                var username = $('.username').val();
                var password = $('.passcode').val();
                var auth = make_basic_auth(username, password);

                jqXHR.setRequestHeader("Authorization",  auth);
                jqXHR.setRequestHeader('Content-Type', 'text/plain');
            },
            success: function (){
               alert("ok");
            },
            error: function (){
               alert("no");
            }
        }
    );
});

Upvotes: 0

Views: 6856

Answers (1)

sv_in
sv_in

Reputation: 14049

Checkout the following code:

$.ajax({
  url: "google.com",
    beforeSend: function(jqXHR, settings) {
        jqXHR.error = function(){
            alert("failed");
        }
    }
})​

Working example: http://jsfiddle.net/kXerD/

Here, I am saying that before sending the request, add a error handler to this request. JQuery provides the objects of jqXHR and settings that is relevant for this request. We don't need to initialize them.

Upvotes: 1

Related Questions