Categories: Snippets

AJAX – Send a Request To a Server

The XMLHttpRequest object is used to exchange data with a server.

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
<html>
<head>
<script>
function showHint(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "gethint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

 

Share

Recent Posts

Selecting Elements in jQuery (jQuery Selectors)

To collect a group of elements, we pass the selector to the jQuery function using…

6 years ago

jQuery library Introduction

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is…

6 years ago

Adjust li width fit with ul width of the outer div/body

HTML:- [crayon-67a5b55f90f34479226054/] CSS:- [crayon-67a5b55f90f38217035181/] JavaScript:- [crayon-67a5b55f90f3a255994702/]  

6 years ago

Customize Input Box using jQuery

Prevent users typing special characters in text box, textarea, etc. [crayon-67a5b55f90fe5079400789/] ^[a-zA-Z]+$ Alphabets ^[a-zA-Z\s]+$ Alphabets…

6 years ago

JavaScript simple form validation with example

Any interactive web site has form input - a place where the users input different…

6 years ago

Clear the browser cache of CSS or JavaScript Using Javascript

[crayon-67a5b55f91209178165496/]  

6 years ago