Reputation: 150
Here is my index.html
<script>
var xml = new XMLHttpRequest();
xml.onreadystatechange = function(){
if (xml.readyState === 4 && xml.status === 200) {
console.log(xml.responseText);
}
}
xml.open("POST", "ajax.php", true);
var data = new FormData();
data.append("name","Sahan");
xml.send(data);
</script>
And here is my ajax.php
<?php
echo "Hello " . $_POST["name"];
?>
When I run this on my localhost result is
Notice: Undefined index: name in C:\xampp\htdocs\chat\ajax.php on line 2
Hello
But when I am using JQuery It is Working Correctly...
And my question is how I send ajax using JavaScript without JQuery..?
Upvotes: 2
Views: 813
Reputation: 16436
You have to pass proper header information along with request when you use ajax with post data
<script>
var xml = new XMLHttpRequest();
xml.onreadystatechange = function(){
if (xml.readyState === 4 && xml.status === 200) {
console.log(xml.responseText);
}
}
xml.open("POST", "ajax.php", true);
//Send the proper header information along with the request
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
/*var data = new FormData();
data.append("name","Stackoverflow");*/
xml.send("name=Stackoverflow");
</script>
Upvotes: 5
Reputation: 732
You can use this code in your javascript function.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "ajax_test.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Stack&lname=Overflow");
for more details Ajax at w3schools
Upvotes: 2