0

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?

miken32
  • 42,008
  • 16
  • 111
  • 154
Mileta Dulovic
  • 1,036
  • 1
  • 14
  • 33

2 Answers2

4

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>
miken32
  • 42,008
  • 16
  • 111
  • 154
  • Thank you a LOT. It works. I am using JS because I want to practice validation and stuff.. Its no fun if I don't know what is happening in background :D Again. Thank you – Mileta Dulovic Nov 14 '19 at 00:41
  • This man need an award. i'm stuck for almost 14 hours find solution why my xhr doesn post whole data to server. special character like & or # make it corrupted. oh, thanks a lot dude! – Hanna Rose Mar 07 '22 at 14:41
3

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

deterjan
  • 348
  • 3
  • 16
  • but I need to send value of 3 variables? can I send all of them with ```xhr.send()```? Or you mean to send text with ```xhr.send()``` and others on with ```data``` – Mileta Dulovic Nov 13 '19 at 23:54
  • sure! you can send whatever you want in the payload and its size limit is very large (see https://stackoverflow.com/questions/2880722/can-http-post-be-limitless/55998160#55998160) – deterjan Nov 13 '19 at 23:56
  • I did it this way ```xhr.send("title=" + title + "&author=" + author + "&text=" + text);``` and it works. I sent about 835k chars and they are all sent. Thank you for your help :) – Mileta Dulovic Nov 14 '19 at 00:10