Search code examples
javascripthttphttp-errorget-request

400 error while making http request in javascript


I ctrl+c the part of Max Payne Wiki article(it's just an exmaple of any text):

just a screenshot of how I copy part of the article

Then I ctrl+v this stuff into <textarea> in my site(not in the code, but literally in the site-rendered <textarea>)

The the runs the next javascript code:

SomeParagraphElement.innerText=document.getElementById('my_txtarea').value;
requestp("aga.php?data="+SomeParagraphElement.innerText, callback_function);

where requestp is

function requestp(path, run)
{
var request = new XMLHttpRequest();
request.open('GET', path, true); 

request.addEventListener('readystatechange' ,function()
{
if ((request.readyState==4) && (request.status==200))
run( request.responseText);
}
);

request.send(null);

}

After this there should be a data uploaded to sever, but it doesn't happen and if I just write stuff from keyboard by my fingers and even insert emojis - all works fine.

Google Chrome debug window says, that I make a 400 HTTP error. I tried

var str= SomeParagraphElement.innerHTML.replace(/(?:\r\n|\r|\n)/g, '%0A'); and another %blahblah symbol, but it doesn't change anything.

If I make a new line by myself by pressing 'enter', via keyboard it works fine.

What should I do?


Solution

  • Yeah, if I pass data more the 2048 bytes, I have to use POST request. Here is a function, maybe it will be helpfull for someone

    function requestp(path, data, callback)
    {
    var request = new XMLHttpRequest();
    request.open('POST', path, true); 
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');//specify this!
    
    request.addEventListener('readystatechange' ,function()
    {
    if ((request.readyState==4) && (request.status==200))
    callback( request.responseText);
    }
    );
    
    request.send(data);
    
    }