I am just starting to learn how to use XMLHttpRequest and I started with this example from w3schools which I want to modify in order to send a string. This is the new code:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
var str="sent string";
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send(str);
alert(xmlhttp.responseText);
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
I want to output the response and see if the string was sent but the alert returns nothing. Just an empty window. What am I doing wrong?
Also, I found an example in this question which also adds these lines of code:
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
Are they always necessary? If yes, why? The code from that page also sends a string but that code doesn't work for me either.
EDIT: This is my updated code, which still doesn't work. I even tried it without sending the string but still nothing happens. I am not trying it anymore in w3wschools, but instead in the right place, I do not have my code in a function anymore and made the changes that @Quentin told me about:
<script>
var xmlhttp=null;
var str="sent_string";
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","http://192.168.1.3:80",true);
xmlhttp.setRequestHeader("Content-type", "text/plain");
xmlhttp.setRequestHeader("Content-length", str.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(str);
xmlhttp.addEventListener('load', function () {
alert(this.responseText);
alert(xmlhttp.readyState);}
);
</script>