5
votes

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

4
why do you need JS? you should be doing this server-side.meder omuraliev
What errors are you getting? Why do you need to use JavaScript?Nicole
You should clarify the question if no one understood it, or accept an answer.Alan H.

4 Answers

9
votes

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.

5
votes

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!

4
votes

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

1
votes

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);
  }
)()