You are on page 1of 10

Physically Detached Yet Academically Attached

SCP-TOPICS: FINAL PERIOD TOPICS

Week 13 Integration of script


Lesson Title Design Patterns and Interfaces
Define the importance of using design patterns, describe what is a
Learning Outcome(s) programming interface and its importance

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

Software Design Pattern a description or template for how to solve


a problem that can be used in many different situations.

Interaction is a kind of action that occurs as two or more objects


have an effect upon one another. The idea of a two-way effect is
essential in the concept of interaction, as opposed to a one-
way causal effect

Best Practice a standard way of complying with legal or ethical


requirements.

Object-oriented design Patterns that imply mutable state may be


unsuited for functional programming languages.

Essential Content

The XMLHttpRequest Object


All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a
web server behind the scenes. This means that it is possible to
update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object


All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera)
have a built-in XMLHttpRequest object.
Physically Detached Yet Academically Attached

Syntax for creating an XMLHttpRequest object:


variable = new XMLHttpRequest();

Access Across Domains


For security reasons, modern browsers do not allow access across
domains.
This means that both the web page and the XML file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the
W3Schools domain.
If you want to use the example above on one of your own web
pages, the XML files you load must be located on your own server.
Physically Detached Yet Academically Attached

AJAX
AJAX stands for Asynchronous JavaScript and XML, and it
allows you to fetch content from the back-end server
asynchronously, without a page refresh. Thus, it lets you update
the content of a web page without reloading it.
Let’s look at an example to understand how you could use
AJAX in your day-to-day application development. Say you want to
build a page that displays a user's profile information, with different
sections like personal information, social information, notifications,
messages, and so on.
The usual approach would be to build different web pages for
each section. So for example, users would click the social
information link to reload the browser and display a page with the
social information. This makes it slower to navigate between
sections, though, since the user has to wait for the browser to
reload and the page to render again each time.
On the other hand, you could also use AJAX to build an
interface that loads all the information without refreshing the page.
In this case, you can display different tabs for all sections, and by
clicking on the tab it fetches the corresponding content from the
back-end server and updates the page without refreshing the
browser. This helps you to improve the overall end-user experience.
AJAX is used to create more interactive applications.

The following example demonstrates how a web page can


communicate with a web server while a user types characters in an
input field.

The overall AJAX call works something like this:


Physically Detached Yet Academically Attached

Let’s quickly go through the usual AJAX flow:

1. First, the user opens a web page as usual with a


synchronous request.
2. Next, the user clicks on a DOM element—usually a button
or link—that initiates an asynchronous request to the
back-end server. The end user won’t notice this since the
call is made asynchronously and doesn’t refresh the
browser. However, you can spot these AJAX calls using a
tool like Firebug.
3. In response to the AJAX request, the server may return
XML, JSON, or HTML string data.
4. The response data is parsed using JavaScript.
5. Finally, the parsed data is updated in the web page's
DOM.
6. So as you can see, the web page is updated with real-time
data from the server without the browser reloading.

How AJAX Works Using Vanilla JavaScript

In this section, we’ll see how AJAX works in vanilla JavaScript.


Of course, there are JavaScript libraries available that make it
easier to do AJAX calls, but it’s always interesting to know what’s
happening under the hood.

Let’s have a look at the following vanilla JavaScript code, which


performs the AJAX call and fetches a response from the server
asynchronously.
Physically Detached Yet Academically Attached

Let’s go through the above code to understand what’s


happening behind the scenes.

1. First, we initialize the XMLHttpRequest object, which is


responsible for making AJAX calls.
2. The XMLHttpRequest object has a readyState property,
and the value of that property changes during the request
lifecycle. It can hold one of four values: OPENED,
HEADERS_RECEIVED, LOADING, and DONE.
3. We can set up a listener function for state changes using
the onreadystatechange property. And that’s what we’ve
done in the above example: we’ve used a function which
will be called every time the state property is changed.
4. In that function, we’ve checked if the readyState value
equals 4, which means the request is completed and we’ve
got a response from the server. Next, we’ve checked if the
status code equals 200, which means the request was
successful. Finally, we fetch the response which is stored
in the responseText property of the XMLHttpRequest
object.
5. After setting up the listener, we initiate the request by
calling the open method of the XMLHttpRequest object.
The readyState property value will be set to 1 after this
call.
6. Finally, we’ve called the send method of the
XMLHttpRequest object, which actually sends the request
to the server. The readyState property value will be set to 2
after this call.
7. When the server responds, it will eventually set the
readyState value to 4, and you should see an alert box
displaying the response from the server.
Physically Detached Yet Academically Attached

Example Explained
In the example above, when a user types a character in the input
field, a function called showHint() is executed.
The function is triggered by the onkeyup event.
<html>
<body>

<p><b>Start typing a name in the input field below:</b></p>

<p>Suggestions: <span id="txtHint"></span></p>

<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>

<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>

</body>
</html>
Physically Detached Yet Academically Attached

Code explanation:
First, check if the input field is empty (str.length == 0). If it is,
clear the content of the txtHint placeholder and exit the function.
However, if the input field is not empty, do the following:
x Create an XMLHttpRequest object
x Create the function to be executed when the server
response is ready
x Send the request off to a PHP file (gethint.php) on the
server
x Notice that q parameter is added gethint.php?q="+str
x The str variable holds the content of the input field

The PHP File - "gethint.php"


The PHP file checks an array of names, and returns the
corresponding name(s) to the browser:
Physically Detached Yet Academically Attached

<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
Physically Detached Yet Academically Attached

// get the q parameter from URL


$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""


if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}

// Output "no suggestion" if no hint was found or output


correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
Physically Detached Yet Academically Attached

Create a simple XMLHttpRequest, and retrieve data


from a TXT file

SELF-SUPPORT: You can click the URL Search Indicator below to help you further understand the lessons.
Search Indicator
https://www.w3schools.com/js/js_ajax_http.asp
https://code.tutsplus.com/tutorials/how-to-use-ajax-in-php-and-jquery--cms

You might also like