Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I find decent jQuery ajax headings setting documentation?

Instead of using the beforeSend method of setting the request headers, I decided I wanted to look into using the headers setting option of a jQuery $.ajax() call. Naturally, I went to this page here, http://api.jquery.com/jQuery.ajax/, but the documentation is scarce and I can't find any way to set multiple headers and the format for doing so on that page, or anywhere else.

@tahir: Then why is this not working?

<!DOCTYPE html>
<html>
  <head>
    <title>Multiple DnD Uploader</title>
    <link rel="stylesheet" href="style.css" />
    <script type = "text/javascript" src = "../music/jquery.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $('#drop').change(function(event){
          files = event.target.files;
          $('#drop').css('display', 'none');
          for(var i = 0, len = files.length; i < len; i++) {
            alert(files[i].fileName);
            $.ajax({
              type: "POST",
              url: "uploader.php",
              contentType: "multipart/form-data",
              headers: {
                "X-File-Name" : ""+files[i].fileName,
                "X-File-Size" : ""+files[i].fileSize
              },
              data: 'hi',
              success: function(data){
                $('#info').append('Success: ' + data + '<br />');
              },error: function(data){
                $('#info').append('Error: ' + data + '<br />');
              }
            });
          }
        });
      });
    </script>
  </head>
  <body>
    <div id="drop">
      <h1>Drop files here</h1>
      <p>To add them as attachments</p>
      <input type="file" multiple="true" id="filesUpload" />
    </div>
    <div id="info">
    </div>
  </body>
</html>

The two X-File-Name and X-File-Size attributes aren't showing up in the request headers.

SOLUTION: I feel really stupid, turns out the particular jquery.js file I was pointing to was 1.4.4, so I upgraded and now it works! Thanks.

like image 323
Vap0r Avatar asked Oct 11 '22 00:10

Vap0r


1 Answers

It says:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

So all you have to do is to pass an object like:

{"header1":"value1","header2":"value2"}

and so on. Here is some code that adds Accept header in a post request:

    $.ajax("relative/url/action.do",{
    success: function(){
        alert("success");
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert(textStatus + ": " + jqXHR.responseText );
    },
    headers: {Accept: "application/json"},
    type : "POST"
});
like image 82
Tahir Akhtar Avatar answered Oct 15 '22 10:10

Tahir Akhtar