Mileta Dulovic
Mileta Dulovic

Reputation: 1064

How can I send really long text to backend with JavaScript?

I have this form which cotains 2 input elements and 1 textarea element.

The textarea is not limited and can have really big content. I want to send that data to backend where it will be processed and written in database. How I can achive this?

This is code I have so far

<script type="text/javascript">
    var form = document.getElementById('blogs_form');

    form.addEventListener('submit', function(event) {
      event.preventDefault();
      var quote = document.getElementById("blog_title").value;
      var author = document.getElementById("author").value;
      var text = document.getElementById("text").value;
      var data = "blog_title=" + quote + "&author=" + author + "&text=" + text;
      console.log(data)

      var xhr = new XMLHttpRequest();
      var url = "http://localhost/backend/blogs.php?" + data;
      xhr.open("POST", url, true);
      xhr.setRequestHeader("Content-Type", "none");
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          var response = xhr.responseText;
          if(response !== 'success') {
            Swal.fire({
              type: 'error',
              text: response,
            })
          } else {
            Swal.fire({
              type: 'success',
              text: 'Blog recorded in database',
            })
          }
        }
      };
      xhr.send();
    })
  </script>

I am sending it by creating XMLHttpRequest() with method POST as you can see in code above.

Problem with this is when I write about 8000 characters it breaks and I get 414 response. Which means that URI is too long.

Is there any way to send as much data as I want? It will be always just text data.

Also. Could it be server side problem? That it has some kind of limits? And if so is there a way to avoid this?

Upvotes: 0

Views: 1746

Answers (2)

miken32
miken32

Reputation: 42718

You should not be building post data manually like this at all. As soon as a user puts in a special character like & or # your data will be corrupted. I would recommend a library like jQuery to handle all this stuff for you, but if you insist on plain Javascript, something like this should work:

<script>
var form = document.getElementById('blogs_form');

form.addEventListener('submit', function(event) {
  event.preventDefault();
  // here is where we serialize all the data from the form automatically
  var data = new FormData(this);
  var xhr = new XMLHttpRequest();
  var url = "http://localhost/backend/blogs.php";
  xhr.open("POST", url, true);
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var response = xhr.responseText;
      if(response !== 'success') {
        Swal.fire({
          type: 'error',
          text: response,
        })
      } else {
        Swal.fire({
          type: 'success',
          text: 'Blog recorded in database',
        })
      }
    }
  };
  // and here it is sent as POST body, not part of URL
  xhr.send(data);
})
</script>

BTW, in jQuery this would look something like:

<script>
$("#blogs_form").on("submit", function(e) {
    e.preventDefault();
    $.post(
        "http://localhost/backend/blogs.php",
        $(this).serialize(),
        function(data, response, xhr) {
            if (response === "success") {
                Swal.fire({type: 'success', text: 'Blog recorded in database'}),
            } else {
                Swal.fire({type: 'error', text: response})
            }
        }
    );
});
</script>

Upvotes: 4

deterjan
deterjan

Reputation: 390

You are using POST method but still appending the long text as a parameter to the URL. To add the text to POST payload:

1) don't append text to data:

var data = "blog_title=" + quote + "&author=" + author;

2) instead of xhr.send();, do this:

xhr.send(text);

Upvotes: 3

Related Questions