packetie
packetie

Reputation: 5069

Why is my Ajax request sending "Content-Type: application/x-www-form-urlencoded" when I have dataType: "JSON"?

When I am using the following to respond to a button click, it it called (verified by using the console.log()), however, the http request it generated has the header "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n". Shouldn't it be json?

I am using google chrome 34.0.1847.132 on Ubuntu. Jquery version 1.8.3.

Thanks in advance!

function action (mode) {
    console.log("action called with mode " + mode);
    $.ajax({
      type: "POST",
      url: '/saas.php',
      data: {
          action: (mode == 1)? "start" : "stop"
      },
      dataType: "json",
      success: function(data) {
          //alert(data);
          if (data.msg != null) {
              alert(data.msg);
          } else {
            if (mode == 1) {
                document.getElementById('createLoadGen').innerHTML = 'creating loadGen...';
                setTimeout(checkStatus, 1000);
            }
          }
      }
    });
    if (mode == 2) {
        document.getElementById('createLoadGen').innerHTML = '<button onclick="action(1)" >create LoadGen</button>';
        document.getElementById('deleteLoadGen').style.display = 'none'
    }
}

Upvotes: 4

Views: 26256

Answers (1)

Quentin
Quentin

Reputation: 943556

Not generally. The Content-Type header in the request describes the content in the request body, not the type of content that is expected in the response (describing the expected response format is the job of the Accept header).

By default, jQuery will encode the data using the standard encoding used by HTML forms.

Now, it might be that the server is expecting the request to be formatted as JSON, in which case you would need to make the following modifications to the jQuery call:

  1. Say that you are sending JSON
  2. Encode the content you are sending as JSON instead of letting jQuery encode it itself

Such:

  data: JSON.stringify({
      action: (mode == 1)? "start" : "stop"
  }),
  contentType: "application/json",

sass.php will then have to parse the JSON request instead of letting PHP do it invisibly in the background and just plucking the data out of $_POST.

Upvotes: 11

Related Questions