-2

Posting a form using AJAX

My AJAX script wasn't working before (it wouldn't send data) but setting the request headers solve the problem. It's great that it works but I want to understand why they are needed for it to work. Thanks :-)

//Send the proper header information along with the request 
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
http.setRequestHeader("Content-length", params.length); 
http.setRequestHeader("Connection", "close"); 

javascript

function request(elm, type, url, str, fn) { 
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
    if (xhr.readyState==4 && xhr.status==200)
    {
        if (!fn) elm.innerHTML=xhr.responseText; 
        else fn(xhr);
    }
}
      xhr.open(type, url, true);
      //yay it works with this :-)
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.send(str);
}

var form = document.getElementById("form_login")
var btnLogin = form.getElementsByClassName("btn")[0];
addEvent(btnLogin, "click", function(e) 
{
    preventDefault(e);
    var post ="",input,inputs = form.getElementsByClassName("input");
    for (var i=0, l=inputs.length; i<l; i++) 
    {
        input = inputs[i].getElementsByTagName("input")[0];
        post += input.name + "=" + encodeURI(input.value) + "&";
    }
    post = post.substr(0,post.length-1);
    var help = form.getElementsByClassName("help")[0];
    request(help, "POST", "user/login-exe.php?dt='" + new Date() + "'", post);
});

and if its all valid it will log the user in that bit isn't shown though.

Community
  • 1
  • 1
manish
  • 497
  • 9
  • 17
  • 1
    Did you do any research? – Marcin Aug 12 '12 at 12:33
  • The first thing that comes to my mind is to ask the guy who answered your last question. – Adi Aug 12 '12 at 12:34
  • How I can't post comments yet. Wait where did this come from? – manish Aug 12 '12 at 12:36
  • @immanish, sorry, my bad. Well, the second thing that comes to my mind is [this](https://google.com/search?q=What+are+request+headers) – Adi Aug 12 '12 at 12:39
  • Thanks but why do i have to set the content-length? and why is connection set to close? do i need all three and why doesn't it work without them. – manish Aug 12 '12 at 12:44
  • 1
    @immanish you really need to post your server-side code. None of them are required. In fact, the later 2 don't do anything as they are something the browser must decide for you. – Esailija Aug 12 '12 at 12:45
  • @immanish: Did you happen to test the script on chrome? and it didn't work out for you? And after setting those headers it worked a charm? – verisimilitude Aug 12 '12 at 12:54
  • @verisimilitude: It works in chrome, Firefox and IE tested on all newest versions. – manish Aug 12 '12 at 13:02

2 Answers2

3

This isn't strictly a requirement, PHP will just automatically populate $_POST when the request specifies content-type of "application/x-www-form-urlencoded".

You can still get access to the values with

file_get_contents("php://input");

In fact, any server should allow you to get access to the raw request body.

The other headers are not doing anything, the browser will not allow you to change them as is specified. If you were able to change them, you would probably report the wrong Content-Length everytime. Because .length counts UTF-16 code units where as Content-Length must be in bytes.

Reference: http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

Terminate these steps if header is a case-insensitive match for one of the following headers:

  • Accept-Charset
  • Accept-Encoding
  • Access-Control-Request-Headers
  • Access-Control-Request-Method
  • Connection
  • Content-Length
  • Cookie
  • Cookie2
  • Content-Transfer-Encoding
  • Date
  • Expect
  • Host
  • Keep-Alive
  • Origin
  • Referer
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • User-Agent
  • Via
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Do I need all three header thingy's or is there a specific one that makes it work. :-) – manish Aug 12 '12 at 12:48
  • @immanish it's just the content-type header, the other ones are not doing anything – Esailija Aug 12 '12 at 12:49
  • I don't think it's necessary too. The default is `application/x-www-form-urlencoded` isn't it? – verisimilitude Aug 12 '12 at 12:50
  • @verisimilitude in chrome, the default is `application/xml`. The specification says that the default must be `text/plain`. – Esailija Aug 12 '12 at 12:51
  • Oh, so it mustn't have worked for the OP when he tested his script on chrome. – verisimilitude Aug 12 '12 at 12:54
  • @verisimilitude it doesn't matter what browser, I don't think any browser has `application/x-www-form-urlencoded` as default. Firefox is following the standard and using `text/plain`. – Esailija Aug 12 '12 at 13:00
  • Oh. :( I'm confused. So you mean @Esailija that none of the browsers encode a `
    `'s data in the default `application/x-www-form-urlencoded`. Terribly confused :(
    – verisimilitude Aug 12 '12 at 13:03
  • @verisimilitude he is not posting a form but sending an `XMLHttpRequest`. I never talked about any form elements and neither did the OP... – Esailija Aug 12 '12 at 13:05
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/15229/discussion-between-verisimilitude-and-esailija) – verisimilitude Aug 12 '12 at 13:06
  • If I am sending passwords do I have to do anything else to my script. I have edited my post to include it. – manish Aug 12 '12 at 13:06
0

1.) "Content-type" header for a <form>: Specifies the content-type to encode the form data set while submitting the form data over to the server.

application/x-www-form-urlencoded: Says to encode the form's data as a.) Control names and values are listed in the order they appear; control name is seperated from it's value by an '=' and control names and values are delimited by an '&' b) Control names and values are escaped. Space characters are replaced with a '+' and other reserved characters are escaped as described in RFC1738.

2) "Content-length" : This header indicates the size of the message body in decimal octets - What's the "Content-Length" field in HTTP header?

3) Connection: The state of the connection.

I don't think so setting "Connection" is required.

Community
  • 1
  • 1
verisimilitude
  • 5,077
  • 3
  • 30
  • 35