Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to implement html button to access REST get resource

Fairly new to REST and web application and would like to create a front-end site with a button and a place where a result is displayed.

I have REST API structured like this: http://hostserver.com/MEApp/MEService

This returns a value when browsing to it.

Now I would like to implement a GUI so that when you browse to c:\resourcebutton.html There will be a button and when I click on it, it will call the REST API resource and returns the result. If I understood REST correctly it should work like this.

I have a html code:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to trigger a function.</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Hello World";
}
</script>

</body>
</html>

How and where should I insert the GET method to call the API? Is it common to use Javascript?

like image 778
JustinBieber Avatar asked Oct 26 '25 14:10

JustinBieber


1 Answers

Yes, you have to do this with JavaScript. In fact, you need Ajax.

To simplify things, you should download and include JQuery to your site, and then use something like this:

$.post( "http://hostserver.com/MEApp/MEService", function( data ) {
  document.getElementById("demo").innerHTML = data;
  //Or, in the JQuery-way:
  $('#demo').html(data);
});

The jQuery Source can be found here: http://code.jquery.com/jquery-2.1.1.js

Your html-file would then look like this:

<!DOCTYPE html>
<html>
<head>
    <script src="the/Path/To/The/Downloaded/JQuery.js"></script>
    <script>
        //Usually, you put script-tags into the head
        function myFunction() {
            //This performs a POST-Request.
            //Use "$.get();" in order to perform a GET-Request (you have to take a look in the rest-API-documentation, if you're unsure what you need)
            //The Browser downloads the webpage from the given url, and returns the data.
            $.post( "http://hostserver.com/MEApp/MEService", function( data ) {
                 //As soon as the browser finished downloading, this function is called.
                 $('#demo').html(data);
            });
        }
    </script>
</head>
<body>

    <p>Click the button to trigger a function.</p>

    <button onclick="myFunction()">Click me</button>

    <p id="demo"></p>    
</body>
</html>
like image 111
maja Avatar answered Oct 29 '25 05:10

maja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!