Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

368 CHAPTER 8 Websites and services


The addition operation uses the GET method as signified by the app.get function call. This
creates a route by which a GET request that matches addition executes the code block. In the
code block, three variables (x, y, and result) are declared and initialized. The x and y param-
eters are retrieved from the QueryString and converted to numbers. Next, the result is popu-
lated by executing the addition method on the math object with x and y. Finally, the response
object is used to write the status code in which 200 is a success, and the content type is set to
return a JSON result. The response object is then used to write the JSON object.
In this example, the JSON object is represented by curly braces. One property is called
result, and its value is set to the result of the addition method call.
At the end of the file, add the following code to start the web service.
var port = 8080;
app.listen(port);
console.log('Listening on port: ' + port);

After saving the app.js file, you can start the web service by executing the following
command.
node app

To test this, you can use the browser, but depending on the browser you use, you might
need to click through several prompts to view the results. Here is the URL.
http://localhost:8080/addition?x=5&y=10

When you finally see the result, it should look like the following.
{ "result": 15}

The code in this example is similar to the code on the math_user website; however, that
site returned HTML, albeit crude HTML, whereas this example returned a JSON object. This is
your web service, but how can you call it from a webpage and use the return object? This is
when AJAX comes into play.

Using AJAX to call a web service


Use AJAX to create asynchronous calls to web services. AJAX is JavaScript. You can think of it
as being advanced JavaScript. Instead of designing a submit button to post the data back to
the server and then watching the screen be repainted, JavaScript calls back to the server and
processes the result without causing a complete repaint of the screen.
Create and consider the following Math.html webpage that is created in the public folder
of math_service.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="/scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/scripts/default.js"></script>
Free download pdf