Posting data via AJAX

The script works fine when doing GET instead of POST. POST fails. I’m not sure what I’m missing.

req.open('post', url, true);req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.send(data);

And data looks like this…

var data = 'letter-customer-name=' + firstname + ' ' + lastname + '&letter-customer-email=' + email + '&letter-sender-name=' + employeename + '&letter-sender-email=' + employeeemail + '&letter-body=' + message;

message holds a bunch of HTML. Could that be an issue?

On the ASP side I have…

mailmessage = new MailMessage(Request.Form["letter-sender-name"] + " <" + Request.Form["letter-sender-email"] + ">", Request.Form["letter-customer-name"] + " <myemail@mydomain.com>", "Sales Contact", message);

Request.QueryString works fine with GET and is easy to test, but I’m not sure what could be failing (if anything) on the ASP side. How do you test a POST page? With a GET it’s easy because you just put it in the URL.

Thanks!

Make a cross-browser instance of the required class

var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

Declare a response handler:

httpRequest.onreadystatechange = processResponse;

Make the request:

var data = "name=Pullo&skillLevel=mighty"

httpRequest.open('POST', 'submit.php', true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.send(null);

On the server do something with the data received:

<?php 
  echo($_POST['name'] . " " . $_POST['skillLevel']);
?>

In the response handler:

function processResponse(){
  if (httpRequest.readyState === 4) {
      // everything is good, the response is received
      if (httpRequest.status === 200) {
          // perfect!
          console.log(httpRequest.responseText);
      } else {
          console.log(httpRequest);
          // there was a problem with the request,
          // for example the response may contain a 404 (Not Found)
          // or 500 (Internal Server Error) response code
      }
  } else {
      // still not ready
  }
}

This way you can see what the server is doing and inspect the response.

Does that help?