Question

I am looking to create a client browser interface which will utilise the dictionary web service at Glosbe API. The user should be able to enter a word or a phrase into an input component and submit it without the page reloading. The returned data needs to be displayed on the page in a usable format so that they are able to find and read the meanings.

I've attempted this by creating a web service through Netbeans but I'm unsure whether this is the right method. Is it as simple as creating a HTML page and using javascript to call the api for Glosbe?

Any help would be highly appreciated.

Was it helpful?

Solution

You can use an XMLHTTPRequest from javascript to poll a web service. The XHR object is great for allowing you to make a request to a page or submit a form without having to refresh the page. When the request is made, it can be done asynchronously to allow the page to continue with other events and then handle the response and update the HTML. There are tons of resources on google that can instruct you on implementing an XHR object and the proper error handling along with sample code.

As far as the returned data being displayed in a usable format, that would need to be done by your JS when the response comes back. You can parse the response for the data you want and build the appropriate HTML element through JS to update your UI.

HTML
<input type='text' id='word'>
<input type='buton' onclick='sendMessage()'>

JS

function sendMessage()
{
 var XHRrequest=new XMLHttpRequest();
 XHRrequest.onabort = function() {
 };
 XHRrequest.onloadend = function (evt) {
 };
 XHRrequest.onreadystatechange = function() {
  if (XHRrequest.readyState == 4 && XHRrequest.status == 200) {
   //parse XHRrequest.responseText for response and build object
   //this is where you update your UI with an HTML element
  }
  else if (XHRrequest.readyState == 4 && XHRrequest.status!=0) {
   console.log("Error: returned status code " + XHRrequest.status + " " + XHRrequest.statusText + "\r\n" + XHRrequest.responseText);
   //error handling for failed response
  }
 };
 XHRrequest.ontimeout = function() {
  alert("Error: event timed out");
 };
 XHRrequest.open("POST", WEBSERVICE_URL_HERE, true);
 XHRrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 XHRrequest.send("word="+document.getElementById('word').value); \\request data goes here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top