Reputation: 389
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>
Upvotes: 1
Views: 6356
Reputation: 943537
First, you aren't waiting for the HTTP response before you try to alert the value.
alert(xmlhttp.responseText);
should be:
xmlhttp.addEventListener('load', function () {
alert(this.responseText);
});
Second, you are making a GET request with a message body. You need a POST (or PUT) request if you want to send a request body:
xmlhttp.open("POST","ajax_info.txt",true);
Third, you are sending a plain text request but telling the server it is form encoded.
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
should be
xmlhttp.setRequestHeader("Content-type", "text/plain");
Upvotes: 2
Reputation: 1967
if you want to send something with an ajax request there are two ways, POST, and GET.
You will have to read about it before sending anything. Just Google for REST, or HTTP POST. You will find everything.
Than I would suggest you to use AngularJS, or jQuery, instead of a raw ajax call.
For example in AngularJS, all you have to do is:
$http.get('mypage.php?name=john').success(function (data) {
//work with the answer in data
});
Upvotes: 0