5

How can you set the Content-Type header to "application/x-www-form-urlencoded; charset=UTF-8" using JavaScript?

I need to do this so I can view a form with french characters without generating errors.

Thanks

Bob K
  • 61
  • 1
  • 1
  • 3

4 Answers4

9

Headers are set by the server delivering the content-type as part of the HTTP message. By the time it's in the browser and running the javascript it's too late. Do you have access to the server-side code? Why not set the content type to utf-8 in there? You can also do it as part of the meta tag in the head.

Parrots
  • 26,658
  • 14
  • 59
  • 78
  • Hi seemingly by adding a tag like you can set the charset at least, do you know how to do this in javascirpt only? – Yaakov5777 Mar 17 '19 at 06:22
5

You can add a meta tag into the head of the page, or send the header server-side.

example,

<meta http-equiv="Content-type" content="application/x-www-form-urlencoded; charset=UTF-8"/>

on the server-side, say PHP:

<?php
  header( 'Content-type: application/x-www-form-urlencoded; charset=UTF-8' );
?>

that's it!

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
4

The content type is set by the server before it sends the HTML to the browser. You can't modify it with JavaScript.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

I assume that you want to communicate with the server, for example, to submit a form, and then the server sends you back the results, in which you need the correct Content-type to allow the server to communicate.

if so, then XMLHttpRequest.setRequestHeader() may help.


an example

(
  () => {
    const form = document.forms.namedItem("my-query-form")
    form.addEventListener('submit', function (submitEvent) {

      const outputElement = document.getElementById("msg")

      const xhr = new XMLHttpRequest();
      xhr.open("POST", "query", true);
      xhr.setRequestHeader("Content-Type", "application/json"); // <----
      xhr.onload = function (oEvent) {
        if (xhr.status === 200) {
          outputElement.innerHTML = `<p style="color:green;">${xhr.responseText}</p>`;
          setTimeout(function () {
            window.location.href = "/home";
          }, 1000);

        } else {
          outputElement.innerHTML = `<p style="color:red;">Error ${xhr.status}: ${xhr.responseText}</p>`
        }
      };

      const htmlFormControlsCollection = submitEvent.target.elements
      const jsonData = JSON.stringify(
        {
          "username": htmlFormControlsCollection["username"].value,
        });
      xhr.send(jsonData);
      submitEvent.preventDefault();
    }, false);
  }
)()
Carson
  • 6,105
  • 2
  • 37
  • 45