How to call existing REST api from a HTML form?

24,363

Typically When user would like to get data from the server. client need to send a request to the server and get a response. Usually programmer will bind a request function with an specific element and events.

In this case you need to bind a request function with form element. As you didn't mention which event you want to happen, so I couldn't tell exactly solution.

The following code is a simple code that call REST API when user type on a text input, and show the result below the input text

Note that replace "URL" with your API call.

<!DOCTYPE html>
<html>
<body>
    <form>
        Keyword:<br>
        <input type="text" name="keyword" onkeyup="callREST()"><br>
    </form>
    <div id="response"></div>

    <script>
        function callREST() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("response").innerHTML = this.responseText;
                }
            };
            xhttp.open("GET", "URL", true);
            xhttp.send();
        }
    </script>
</body>
</html>
Share:
24,363
BlueBull
Author by

BlueBull

Updated on March 04, 2020

Comments

  • BlueBull
    BlueBull about 4 years

    I have a REST API that I am using in a mobile application to register/store data into a Mongo database. I would now like to view the data stored in the DB on a webpage.

    I know that I basically have all of the functionality already (the login request used in my mobile application) but I am so confused on how to call my REST from my HTML page.

    Something like this: How to call a REST web service API from Javascript button Handler? ?

    I am also confused on how/where I should be creating my html page. Any help is appreciated.

    Thanks, Joe

  • BlueBull
    BlueBull about 6 years
    I just need to log in and if log in is successful show a list of users. I am unsure what my API call is supposed to look like, not used anything like this outside of Android Studio