8

I've been stuck from this issue in couple of days. I want to send some headers data in jQuery.load(). It seems that jQuery.load never send the headers, like ajax. Can somebody explain how to, or Is it necessary? Btw, sory my bad English.

This is the syntax :

$loadingBay.load(href, settings.data, function (data, status) {
    prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents());
});

Many Thanks

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
Rocky Andra
  • 237
  • 1
  • 2
  • 8
  • 1
    I think you need to use the plain ajax function. ($.ajax) – Royi Namir Nov 19 '13 at 08:55
  • 2
    What is the issue with `$.ajax()` is this can't do the job you want to do with `.load()`? – Jai Nov 19 '13 at 08:56
  • I have tried, and it was unsuccessfull. The syntax is bellow : $loadingBay.load(href, settings.data, function (data, status) { prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents()); }); – Rocky Andra Nov 19 '13 at 08:57
  • .load() is a wrapper for .get(), .get() is a wrapper for .ajax(). You can recreate load with the .ajax() method and then add the headers – Liam Nov 19 '13 at 09:01
  • possible duplicate of [How can I add a custom HTTP header to ajax request with js or jQuery?](http://stackoverflow.com/questions/7686827/how-can-i-add-a-custom-http-header-to-ajax-request-with-js-or-jquery) – Liam Nov 19 '13 at 09:02
  • Actually, It's slightly different to my case @Liam – Rocky Andra Nov 19 '13 at 09:28

2 Answers2

8

You can not pass headers data to $.load() , but you can set default setup using $.ajaxSetup() like this :

$.ajaxSetup({
    'headers':{
        'header1':'value1',
        'header2':'value2',
    }
}
);

//give the load call here
$('selector').load('url',function(){
    //do things
})

Disclaimer From jquery doc:

Its use is not recommended.

The best way is do the is thing using $.ajax() :

$.ajax({
  url: "test.html",
  headers : {header1 : "header1"}       
  }).done(function(data) {
     $('selector').html(data);
});
Liam
  • 27,717
  • 28
  • 128
  • 190
MD. Sahib Bin Mahboob
  • 20,246
  • 2
  • 23
  • 45
5

You can use beforeSend option in jquery ajax , like as follows :

$.ajax({
    url: "http://localhost/restTest",
    data: { uname: "asdf" },
    type: "GET",
    beforeSend: function(xhr){xhr.setRequestHeader('X-TOKEN', 'xxxxx');},
    success: function() { alert('Success!' + authHeader); }
});

or can also use headers like,

$.ajax({
    url: "http://localhost/restTest",
    data: { uname: "asdf" },
    type: "GET",
    headers:{ "X-TOKEN": 'xxxxx'},
    success: function() { alert('Success!' + authHeader); }
});
Prabhuram
  • 1,268
  • 9
  • 15