Making web apps dynamic with jQuery and AJAX



jQuery

jQuery is a JavaScript library that specializes in working with the DOM to make web pages dynamic.

jQuery is designed to simplify tasks of JavaScript by writing less code:

  • Animations
  • Event handling
  • DOM manipulation

Installing jQuery

There are two ways get jQuery on to your website:

  • Download the jQuery library from jQuery.com and then include it in your HTML code
  • You can include the jQuery library into your HTML code directly from Content Delivery Network (CDN)

The following code select a HTML element and perform some action:

<head>
<title>jQuery Example</title>
<style type="text/css">
    #div1 {
        background-color: green;
        height: 100px;
        width: 100px;
        position: absolute;
    }
</style>
</head>
<body>
<h2>jQuery Example</h2>
<button>Animation</button>
<br /><br />
<div id="div1"> </div>
<script type="text/javascript">
        // USING CDN
	src="https://code.jquery.com/jquery-3.1.1.min.js"
	integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
	crossorigin="anonymous">
</script>
<script type="text/javascript">
    $(document).ready(function () {
        $('button').click(function () {
            var div = $('#div1');
            div.animate({ height: '300px', opacity: '0.4' }, 'slow');
            div.animate({ height: '300px', opacity: '0.8' }, 'slow');
            div.animate({ height: '100px', opacity: '0.4' }, 'slow');
            div.animate({ height: '100px', opacity: '0.8' }, 'slow');
        });
    });
</script>
</body>

jQuery is easy to use, it’s stable, fully documented, and it works well with other frameworks. In the following Table are listed the categories of functionality that jQuery provides.

Categories Functionality
Ajax Methods that provide synchronous and asynchronous calls to the server
Attributes Methods that get and set attributes of document object model (DOM) elements
Callbacks object An object that provides many methods for managing callbacks
Core Methods that provide core jQuery functionality
CSS Methods that get and set CSS-related properties
Data Methods that assist with associating arbitrary data with DOM elements
Deferred object A chainable object that can register multiple callbacks into callback queues and relay the success or failure state of any synchronous or asynchronous functions
Dimensions Helper methods for retrieving and setting DOM element dimensions
Effects Animation techniques that can be added to your webpage
Events Methods that provide the ability to register code to execute when the user interacts with the browser
Forms Methods that provide functionality when working with form controls
Offset Methods for positioning DOM elements
Selectors Methods that provide the ability to access DOM elements by using CSS selectors
Traversing Methods that provide the ability to traverse the DOM
Utilities Utility methods

AJAX, Asynchronous JavaScript and XML

Ajax (Asynchronous JavaScript and XML) is really a set of web technologies working together on the client-side to create asynchronous Web applications:

  • XHTM Land CSS for markup
  • DOM for display & interaction
  • XMLand XSLT for data interchange & manipulation
  • JSON for marshalling objects
  • XMLHttpRequest for asynchronous communication
  • JavaScript for tying it all together

The use of AJAX allow you to make server-side requests via JavaScript without having to request a full page refresh. The AJAX call has a few important parameters listed in the following Table::

Parameters Description
url the AJAX call will be requesting. For security reasons, to prevent cross-site scripting, this URL must be within the same domain as the webpage itself.
cache It is optional and indicates whether the call can use a cached copy.
datatype indicates the expected data type, which could be XML or JavaScript Object Notation (JSON).
type GET (default) to request data from the server and POST to post data to the server
success property This parameter takes a function that the results of the AJAX calls should be passed into for the webpage to do some work with
error property Handling error conditions gracefully

The following code makes an AJAX call to the server for the correct data set (hard-coded XML file) that matches the search term:

<body>
<script type="text/javascript">
    $.ajax({
          url: searchPath,
          cache: false,
          dataType: "xml",
          type: "GET", //GET (default) to request, POST to post data
          success: function (data) { ...
          },
          error: function (xhr, textStatus, errorThrown) {
              $('#searchResults').append(errorThrown);
          }
    });
</script>
</body>

The error function is passed three useful parameters: the HTTP request itself, the HTTP error number (such as 404), the error text (such as Not Found).

jQuery and AJAX

You can implement AJAX and jQuery to request data from a server and then use the various DOM manipulation techniques. Making request to the server by using jQuery and AJAX is much more desirable and ease of use.

The following code demonstrates a server call for the correct data (hard-coded XML) set that matches the search term:

<body>
    <h2>jQuery & Ajax  - Search </h2>
    <div>
        Enter search term: <input type="text" id="searchFruit" />
        <input type="button" id="searchButton" value="Search" />
    </div>
    <div><h1>Results:</h1> </div>
    <div id="searchResults"> </div>
    // USING CDN
<script src="https://code.jquery.com/jquery-3.4.1.min.js"> </script>
<script type="text/javascript">
    window.onload = function () {
        $('#searchButton').click(function () {
            var searchPath;
            $('#searchResults').empty();
            switch ($('#searchFruit').val()) {
                case 'long':
                    searchPath = "Fruit/Blue.xml";
                    break;
                case 'round':
                    searchPath = "Fruit/Red.xml";
                    break;
                case 'orange':
                    searchPath = "Fruit/Orange.xml";
                    break;
                default:
                    InvalidSearchTerm();
            }
            $.ajax({
                url: searchPath,
                cache: false,
                dataType: "xml",
                success: function (data) {
                    $(data).find("fruit").each(
                        function () {
                            $('#searchResults').append($(this).text());
                            $('#searchResults').append("<BR />");
                        })
                },
                error: function (xhr, textStatus, errorThrown) {
                    $('#searchResults').append(errorThrown);
                }
            });
        });
    }
    function InvalidSearchTerm() {
        $('#searchResults').empty();
        $('#searchResults').append('Invalid Search Term. Please try again.');
    }
</script>
</body>

Ads Right