Quick Contact

    jQuery Introduction

    jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML.It is free, open-source software using the permissive MIT License. Web analysis indicates that it is the most widely deployed JavaScript library by a large margin.

    jQuery’s syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also provides capabilities for developers to create plug-ins on top of the JavaScript library. This enables developers to create abstractions for low-level interaction and animation, advanced effects and high-level, theme able widgets. The modular approach to the jQuery library allows the creation of powerful dynamic web pages and Web applications.

    jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript. The following points describe best of jQuery:

    • jQuery is a lightweight, write less, do more, JavaScript library.
    • The purpose of jQuery is to make it much easier to use JavaScript on your website.
    • jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish and wraps them into methods that you can call with a single line of code.
    • jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

    The jQuery library contains the following features:

    • HTML/DOM manipulation
    • CSS manipulation
    • HTML event methods
    • Effects and animations
    • AJAX
    • Utilities
    Adding jQuery to Your Web Pages

    There are several ways to start using jQuery on your web site. You can:

    • Download the jQuery library from jQuery.com
    • Include jQuery from a CDN, like Google
    Downloading jQuery

    There are two versions of jQuery available for downloading:

    • Production version – this is for your live website because it has been minified and compressed
    • Development version – this is for testing and development (uncompressed and readable code)

    Both versions can be downloaded from jQuery.com.

    The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice that the <script> tag should be inside the <head> section):

    <head>
    <script src="jquery-3.3.1.min.js"></script>
    </head>
    

    Note: Place the downloaded file in the same directory as the pages where you wish to use it.

    jQuery CDN

    If you don’t want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).

    Both Google and Microsoft host jQuery.

    To use jQuery from Google or Microsoft, use one of the followings:

    • Google CDN:
      <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      </head>
      
    • Microsoft CDN:
      <head>
      <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
      </head>
      
    jQuery Syntax

    The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

    Basic syntax is: $(selector).action()

    • A $ sign to define/access jQuery
    • A (selector) to “query (or find)” HTML elements
    • A jQuery action() to be performed on the element(s)
    Examples:
    $(this).hide() - hides the current element.
    $("p").hide() - hides all <p> elements.
    $(".test").hide() - hides all elements with class="test".
    $("#test").hide() - hides the element with id="test".
    
    The Document Ready Event

    You might have noticed that all jQuery methods in our examples, are inside a document ready event:

    $(document).ready(function(){
    
       // jQuery methods go here...
    
    });
    

    This is to prevent any jQuery code from running before the document is finished loading (is ready).

    It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

    Here are some examples of actions that can fail if methods are run before the document is fully loaded:

    • Trying to hide an element that is not created yet
    • Trying to get the size of an image that is not loaded yet

    Note: The jQuery team has also created an even shorter method for the document ready event:

    $(function(){
    
       // jQuery methods go here...
    
    });
    
    jQuery Selectors , Events , DOM , Animations
    Selectors

    jQuery selectors are one of the most important parts of the jQuery library.jQuery selectors allow you to select and manipulate HTML element(s).

    jQuery selectors are used to find (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It’s based on the existing CSS Selectors, and in addition, it has some own custom selectors.

    All selectors in jQuery start with the dollar sign and parentheses: $().

    The element Selector

    The jQuery element selector selects elements based on the element name.

    You can select all <p> elements on a page like this:

    $(“p”)

    Example:

    When a user clicks on a button, all <p> elements will be hidden:

    $(document).ready(function(){
        $("button").click(function(){
            $("p").hide();
        });
    });
    
    The #id Selector

    The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

    An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

    To find an element with a specific id, write a hash character, followed by the id of the HTML element:

    $(“#test”)

    Example

    When a user clicks on a button, the element with id=”test” will be hidden:

    $(document).ready(function(){
        $("button").click(function(){
            $("#test").hide();
        });
    });
    
    The .class Selector

    The jQuery class selector finds elements with a specific class.

    To find elements with a specific class, write a period character, followed by the name of the class:

    $(“.test”)

    Example

    When a user clicks on a button, the elements with class=”test” will be hidden:

    $(document).ready(function(){
        $("button").click(function(){
            $(".test").hide();
        });
    });
    
    Events

    jQuery is tailor-made to respond to events in an HTML page. All the different visitor’s actions that a web page can respond to are called events. An event represents the precise moment when something happens.

    Examples of event:
    • moving a mouse over an element
    • selecting a radio button
    • clicking on an element

    The term fires/fired is often used with events. Example: “The keypress event is fired, the moment you press a key”.

    Here are some common DOM events:

    Mouse Events Keyboard Events Form Events Document/Window Events
    click keypress submit load
    dblclick keydown change resize
    mouseenter keyup focus scroll
    mouseleave   blur unload
    jQuery Animations

    jQuery can be used to make animations like slide, fade, etc.

    jQuery hide() and show()

    With jQuery, you can hide and show HTML elements with the hide() and show() methods:

    An example is

    $("#hide").click(function(){
        $("p").hide();
    });
    
    $("#show").click(function(){
        $("p").show();
    });
    
    Syntax:
    $(selector).hide(speed,callback);
    
    $(selector).show(speed,callback);
    

    The optional speed parameter specifies the speed of the hiding/showing and can take the following values: “slow”, “fast”, or milliseconds.

    The optional callback parameter is a function to be executed after the hide() or show() method completes (you will learn more about callback functions in a later chapter).

    The following example demonstrates the speed parameter with hide():

    An example is shown below:

    $("button").click(function(){
        $("p").hide(1000);
    });
    
    jQuery toggle()

    With jQuery, you can toggle between the hide() and show() methods with the toggle() method.

    Shown elements are hidden and hidden elements are shown:

    An example is shown below:

    $("button").click(function(){
        $("p").toggle();
    });
    
    Syntax:
    $(selector).toggle(speed,callback);

    The optional speed parameter can take the following values: “slow”, “fast”, or milliseconds. The optional callback parameter is a function to be executed after toggle() completes.

    jQuery Conflict

    The jQuery library and virtually all of its plugins are contained within the jQuery namespace. As a rule, global objects are stored inside the jQuery namespace as well, so you shouldn’t get a clash between jQuery and any other library (like prototype.js, MooTools, or YUI).

    That said, there is one caveat: by default, jQuery uses $ as a shortcut for jQuery. Thus, if you are using another JavaScript library that uses the $ variable, you can run into conflicts with jQuery. To avoid these conflicts, you need to put jQuery in no-conflict mode immediately after it is loaded onto the page and before you attempt to use jQuery in your page.

    As you already know; jQuery uses the $ sign as a shortcut for jQuery. There are many other popular JavaScript frameworks like: Angular, Backbone, Ember, Knockout, and more. What if other JavaScript frameworks also use the $ sign as a shortcut? If two different frameworks are using the same shortcut, one of them might stop working.

    The jQuery team have already thought about this and implemented the noConflict() method.

    The jQuery noConflict() Method

    The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.You can of course still use jQuery, simply by writing the full name instead of the shortcut:

    An example is shown below:

    $.noConflict();
    jQuery(document).ready(function(){
        jQuery("button").click(function(){
            jQuery("p").text("jQuery is still working!");
        });
    });
    

    You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a variable, for later use. Here is an example:

    An example is shown below:

    var jq = $.noConflict();
    jq(document).ready(function(){
        jq("button").click(function(){
            jq("p").text("jQuery is still working!");
        });
    });
    

    If you have a block of jQuery code which uses the $ shortcut and you do not want to change it all, you can pass the $ sign in as a parameter to the ready method. This allows you to access jQuery using $, inside this function – outside of it, you will have to use “jQuery”:

    An example is shown below:

    $.noConflict();
    jQuery(document).ready(function($){
        $("button").click(function(){
            $("p").text("jQuery is still working!");
        });
    });
    
    Ajax Implementation

    AJAX is the art of exchanging data with a server and updating parts of a web page – without reloading the whole page.

    AJAX = Asynchronous JavaScript and XML.

    In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.

    Examples of applications using AJAX: Gmail, Google Maps, YouTube, and Facebook tabs.

    jQuery provides several methods for AJAX functionality.With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post – And you can load the external data directly into the selected HTML elements of your web page!

    jQuery load() Method

    The jQuery load() method is a simple, but powerful AJAX method.

    The load() method loads data from a server and puts the returned data into the selected element.

    Syntax:
    $(selector).load(URL,data,callback);

    The required URL parameter specifies the URL you wish to load.

    The optional data parameter specifies a set of querystring key/value pairs to send along with the request.

    The optional callback parameter is the name of a function to be executed after the load() method is completed.

    Here is the content of our example file: “demo_test.txt”:

    <h2>jQuery and AJAX are FUN!!!</h2> <p id=”p1″>This is some text in a paragraph.</p>

    The following example loads the content of the file “demo_test.txt” into a specific <div> element:

    An example is shown below:

    $("#div1").load("demo_test.txt");

    It is also possible to add a jQuery selector to the URL parameter.

    The following example loads the content of the element with id=”p1″, inside the file “demo_test.txt”, into a specific <div> element:

    An example is shown below:

    $("#div1").load("demo_test.txt #p1");

    The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:

    • responseTxt – contains the resulting content if the call succeeds
    • statusTxt – contains the status of the call
    • xhr – contains the XMLHttpRequest object

    The following example displays an alert box after the load() method completes. If the load() method has succeeded, it displays “External content loaded successfully!”, and if it fails it displays an error message:

    An example is shown below:

    $("button").click(function(){
        $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
            if(statusTxt == "success")
                alert("External content loaded successfully!");
            if(statusTxt == "error")
                alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });
    

    The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.

    HTTP Request: GET vs. POST

    Two commonly used methods for a request-response between a client and server are: GET and POST.

    • GET – Requests data from a specified resource
    • POST – Submits data to be processed to a specified resource

    GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.

    POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

    jQuery $.get() Method
    $.get(URL,callback);

    The required URL parameter specifies the URL you wish to request.The optional callback parameter is the name of a function to be executed if the request succeeds.

    The following example uses the $.get() method to retrieve data from a file on the server:

    An example is shown below:

    $("button").click(function(){
        $.get("demo_test.asp", function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
    

    The first parameter of $.get() is the URL we wish to request (“demo_test.asp”).

    The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

    Tip: Here is how the ASP file looks like (“demo_test.asp”):

    <%
    response.write("This is some text from an external ASP file.")
    %>
    
    jQuery $.post() Method

    The $.post() method requests data from the server using an HTTP POST request.

    Syntax:
    $.post(URL,data,callback);

    The required URL parameter specifies the URL you wish to request.The optional data parameter specifies some data to send along with the request.The optional callback parameter is the name of a function to be executed if the request succeeds.

    The following example uses the $.post() method to send some data along with the request:

    $("button").click(function(){
        $.post("demo_test_post.asp",
        {
            name: "Donald Duck",
            city: "Duckburg"
        },
        function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
    

    The first parameter of $.post() is the URL we wish to request (“demo_test_post.asp”).Then we pass in some data to send along with the request (name and city).The ASP script in “demo_test_post.asp” reads the parameters, processes them, and returns a result.The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

    Note: Here is how the ASP file looks like (“demo_test_post.asp”):

    <%
    dim fname,city
    fname=Request.Form("name")
    city=Request.Form("city")
    Response.Write("Dear " & fname & ". ")
    Response.Write("Hope you live well in " & city & ".")
    %>
    
    CRUD Operation with AJAX

    The idea behind the CRUD operations is to empower the users so that they could use the app to the maximum. All the information generated or modified through CRUD operations is stored in a database (generally MySQL).

    To help budding developers, lets demonstrate a simple inline CRUD app using jQuery and AJAX.

    Prerequisites

    For this process. The setup requires following things to be installed in your system.

    • PHP7
    • JQuery
    • MYSQL
    Create the Database and Tables

    The step is the creation of the database and the relevant tables. You can use phpadmin for this

    Next, create a table named posts_db through the following query:

    CREATE TABLE IF NOT EXISTS `posts` (
    `id` int(8) NOT NULL,
      `post_title` varchar(255) NOT NULL,
      `description` text NOT NULL,
      `post_at` date DEFAULT NULL
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
    
    Setup Database Connection

    To create the database connection, create a file named dbcontroller.php. Paste the following code into it:

    class DBController {
    private $conn = "";
    private $host = "localhost";
    private $user = "root";
    private $password = "";
    private $database = "blog_samples";
    function __construct() {
    $conn = $this->connectDB();
    if(!empty($conn)) {
    $this->conn = $conn;
    }
    }
    function connectDB() {
    $conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
    return $conn;
    }
    }
    
    Insert, Update, and Delete Functions

    In the DBController class, there is a connectDB function. This is the perfect place for adding the functions for insert, update and delete functions. Here is the code for these functions:

    function runSelectQuery($query) {
    $result = mysqli_query($this->conn,$query);
    while($row=mysqli_fetch_assoc($result)) {
    $resultset[] = $row;
    }
    if(!empty($resultset))
    return $resultset;
    }
    function executeInsert($query) {
            $result = mysqli_query($this->conn,$query);
            $insert_id = mysqli_insert_id($this->conn);
    return $insert_id;
        }
    function executeUpdate($query) {
            $result = mysqli_query($this->conn,$query);
            return $result;
        }
    function executeQuery($sql) {
    $result = mysqli_query($this->conn,$sql);
    return $result;
        }
    function numRows($query) {
    $result  = mysqli_query($this->conn,$query);
    $rowcount = mysqli_num_rows($result);
    return $rowcount;
    }
    
    Add Information to the Database

    To add data to the database, create a file named add.php and add the following code to it:

    <?php
    require_once("dbcontroller.php");
    $db_handle = new DBController();
    if(!empty($_POST["title"])) {
    $title = mysql_real_escape_string(strip_tags($_POST["title"]));
    $description = mysql_real_escape_string(strip_tags($_POST["description"]));
      $sql = "INSERT INTO posts (post_title,description) VALUES ('" . $title . "','" . $description . "')";
      $faq_id = $db_handle->executeInsert($sql);
    if(!empty($faq_id)) {
    $sql = "SELECT * from posts WHERE id = '$faq_id' ";
    $posts = $db_handle->runSelectQuery($sql);
    }
    ?>
    <tr class="table-row" id="table-row-<?php echo $posts[0]["id"]; ?>">
    <td contenteditable="true" onBlur="saveToDatabase(this,'post_title','<?php echo $posts[0]["id"]; ?>')" onClick="editRow(this);"><?php echo $posts[0]["post_title"]; ?></td>
    <td contenteditable="true" onBlur="saveToDatabase(this,'description','<?php echo $posts[0]["id"]; ?>')" onClick="editRow(this);"><?php echo $posts[0]["description"]; ?></td>
    <td><a class="ajax-action-links" onclick="deleteRecord(<?php echo $posts[0]["id"]; ?>);">Delete</a></td>
    </tr>
    <?php } ?>
    
    Edit the Data in the Database

    To edit information in the database, create a file named edit.php and add the following code to it:

    Delete the Data in the Database

    In order to delete information from the database, create a file named delete.php and add the following code to it:

    Bringing It All Together

    It is time to create the form that will act as the view (front-end) of the app. Create the index.php and add the following code to it:

    <?php
    require_once("dbcontroller.php");
    $db_handle = new DBController();
    $sql = "SELECT * from posts";
    $posts = $db_handle->runSelectQuery($sql);
    ?>
    <table class="tbl-qa">
    <thead>
    <tr>
    <th class="table-header">Title</th>
    <th class="table-header">Description</th>
    <th class="table-header">Actions</th>
    </tr>
    </thead>
    <tbody id="table-body">
    <?php
    if(!empty($posts)) { 
    foreach($posts as $k=>$v) {
      ?>
    <tr class="table-row" id="table-row-<?php echo $posts[$k]["id"]; ?>">
    <td contenteditable="true" onBlur="saveToDatabase(this,'post_title','<?php echo $posts[$k]["id"]; ?>')" onClick="editRow(this);"><?php echo $posts[$k]["post_title"]; ?></td>
    <td contenteditable="true" onBlur="saveToDatabase(this,'description','<?php echo $posts[$k]["id"]; ?>')" onClick="editRow(this);"><?php echo $posts[$k]["description"]; ?></td>
    <td><a class="ajax-action-links" onclick="deleteRecord(<?php echo $posts[$k]["id"]; ?>);">Delete</a></td>
    </tr>
    <?php
    }
    }
    ?>
    </tbody>
    </table>
    
    AJAX Inline Add Functionality

    Now we will create the Save and Cancel inline functionality through the native append and remove jQuery functions. The following code will use these functions, save the information in the database and download the loader.gif:

    <script>
    function createNew() {
    $("#add-more").hide();
    var data = '<tr class="table-row" id="new_row_ajax">' +
    '<td contenteditable="true" id="txt_title" onBlur="addToHiddenField(this,\'title\')" onClick="editRow(this);"></td>' +
    '<td contenteditable="true" id="txt_description" onBlur="addToHiddenField(this,\'description\')" onClick="editRow(this);"></td>' +
    '<td><input type="hidden" id="title" /><input type="hidden" id="description" /><span id="confirmAdd"><a onClick="addToDatabase()" class="ajax-action-links">Save</a> / <a onclick="cancelAdd();" class="ajax-action-links">Cancel</a></span></td>' +
    '</tr>';
      $("#table-body").append(data);
    }
    function cancelAdd() {
    $("#add-more").show();
    $("#new_row_ajax").remove();
    }
    function addToDatabase() {
      var title = $("#title").val();
      var description = $("#description").val();
      $("#confirmAdd").html('<img src="loaderIcon.gif" />');
      $.ajax({
    url: "add.php",
    type: "POST",
    data:'title='+title+'&description='+description,
    success: function(data){
      $("#new_row_ajax").remove();
      $("#add-more").show();  
      $("#table-body").append(data);
    }
      });
    }
    function addToHiddenField(addColumn,hiddenField) {
    var columnValue = $(addColumn).text();
    $("#"+hiddenField).val(columnValue);
    }
    </script>
    
    AJAX Inline Edit & Delete Functionalities

    On the blur event of the editable column, create the Edit that removes the row from first the UI and then the database. Here is the code:

    <script>
    function saveToDatabase(editableObj,column,id) {
      $(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat right");
      $.ajax({
    url: "edit.php",
    type: "POST",
    data:'column='+column+'&editval='+$(editableObj).text()+'&id='+id,
    success: function(data){
      $(editableObj).css("background","#FDFDFD");
    }
      });
    }
    function deleteRecord(id) {
    if(confirm("Are you sure you want to delete this row?")) {
    $.ajax({
    url: "delete.php",
    type: "POST",
    data:'id='+id,
    success: function(data){
      $("#table-row-"+id).remove();
    }
    });
    }
    }
    </script>
    
    Summary

    Below given points summarizes the topics as discussed:

    • jQuery is a free, open-source cross-platform JavaScript library designed to simplify the client-side scripting of HTML.
    • jQuery’s syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications.
    • jQuery selectors allow you to select and manipulate HTML element(s).
    • An event represents the precise moment when something happens. For example, moving a mouse over an element, selecting a radio button
    • jQuery provides methods to manipulate DOM in efficient way, attr(), .html(), and .val(), etc. are some methods to manipulate DOM.
    • Accordions displays collapsible content panels for presenting information in a limited amount of space.
    • Carousel is a component for cycling through elements, like a slideshow.
    • A tab is a single content area with multiple panels, each associated with a header in a list.
    • The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it and there will be no nay conflicts.
    • AJAX (Asynchronous JavaScript and XML) is the art of exchanging data with a server and updating parts of a web page – without reloading the whole page.
    • jQuery provides different method to get request from served. They are part of AJAX.
    • It is easy to do CRUD app using jQuery and AJAX. jQuery provides all the method to do so.

    Copyright 1999- Ducat Creative, All rights reserved.