Mohamed Karam Mohamed Karam - 2 months ago 6
Ajax Question

How to know if AJAX request is performed?

I am learning AJAX,
so I have this HTML code:

<!DOCTYPE html>
<html>
<head>
<title>
My first chat page
</title>
<meta charset = "utf-8">
<style>
#message-area {
position: fixed;
bottom: 0;
width: 100%;
}
#send-button {
float: right;
margin: 20px;
color: white;
background-color: green;
}
textarea {
float: left;
width: 90%;
height: 4em;
font-family: cursive;
fon-size: 20px;
resize: none;
}

</style>
</head>
<body>


<div id="message-area">
<textarea id="myTextarea" >
</textarea>
<button type="button" id="send-button">
Send
</button>

</div>
</body>
<script>
var sendButton = document.getElementById("send-button");

function trial(){
var xhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
sendButton.innerHTML = this.responseText;
}
xhttp.open("GET", "insertmessage.php", true);
xhttp.send();
}
}

sendButton.addEventListener("click", trial);

</script>
</html>


And I have this simple PHP code:

<?php
echo "hello";
?>


What I want is that when I click the send button, it sets up an AJAX connection, connects to the server, the server sends "Hello", and change the inner HTML of the send button. I tried them in the same folder in WAMP www directory, but it didn't work.

Answer

just place

xhttp.open("GET", "insertmessage.php", true);
xhttp.send();

outside

xmlhttp.onreadystatechange = function(){
}

your ajax is not send because this code is never executed since you put it inside your onreadystatechange event (this event only occur when your ajax request is send)

xhttp.open("GET", "insertmessage.php", true);
xhttp.send();

so your code would look like this

var sendButton = document.getElementById("send-button");

function trial(){
    var xhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            sendButton.innerHTML = this.responseText;
        }
    }
    xhttp.open("GET", "insertmessage.php", true);
    xhttp.send();

}

sendButton.addEventListener("click", trial);
Comments