[Solved]: How to use jQuery with Node.js with Examples

Getting started to use jQuery with Node.js

Learning how to use jQuery with Node.js enables you to exploit jQuery's potential in building interactive applications efficiently. You can use jQuery on the server-side using the jquery module and jsdom.

// import jsdom
const jsdom = require('jsdom')

// create a window with the document object
const dom = new jsdom.JSDOM("")

// import jquery and supply it with the new dom
const jQuery = require('jquery')(dom.window)

// use jQuery
jQuery([selector]).[action]

OR

Advertisement

have jQuery on the frontend and link it with a Node.js backend.

This tutorial teaches you how to use jQuery with Node.js on the server side and through frontend jQuery with a Node web server.

It starts by explaining the need for combining the two technologies and how each technology works. It then walks you through a step-by-step implementation of the knowledge acquired.

Let's get started.

 

Understanding how jQuery works

This section presents an overview of jQuery to enable you to apply it comfortably in the subsequent sections.

jQuery has built-in functions for animations, effects, and DOM traversal. The functions, which follow the selector-action model, are piped into the global jQuery object, written as jQuery or abbreviated as $.

Advertisement
$(document).ready(function () {
  $([selector]).[action]
})

The action is a method like hide(). You can chain multiple methods or use a method in a callback function to another.

$(document).ready(function () {
  
  // chain methods
  $('div').css().hide()
  
  // use callbacks
  $('button').on('click', function () {
    $('div').toggle(2000)
  })
})

You can also get or post data to an API using jQuery and AJAX. For example, as you will see in the examples section, you can post data to a Node.js server endpoint using $.ajax or $.post method.

$(document).ready(function() {
    $('button').on('click', function() {
        $.ajax({
            type: [e.g GET or POST],
            url: [API endpoint],
          // for POST type
            data: [data to post to the endpoint],
            contentType: [e.g application/json or text/html],
            dataType: [e.g json],
            success: function (data) {
               //handle the returned data
            },
            error: function (error) {
                // handle the error
            }
        });
    })
})

The attributes mainly handle the string data type. For example, you should surround the type's value with quotation marks.

type: 'POST',
// OR
type: "POST",

Now that you understand the technologies we will use, let's set up a lab and practice how to use jQuery with Node.js.

 

Set up Lab Environment

In this section, we will create directories for implementing jQuery with Node.js server-side and client-side jQuery and AJAX with server-side Node.js, respectively. You should have installed Node.js and a preferred code editor.

 

jQuery with Node.js server-side

Open a terminal, create the working directory, then cd into it. Initialize the project, and create the script file. Lastly, install the needed tools.

Advertisement
mkdir jquery_server_side
cd jquery_server_side
npm init -y
touch index.js
npm i jquery jsdom

I have created the jquery_server_side project directory, navigated into it, and initialized a default npm project. I then created the index.js script file and installed jquery and jsdom.

[Solved]: How to use jQuery with Node.js with Examples

 

jQuery on the frontend + Node.js on the backend

Get the full code on the attached GitHub repository before diving into examples.

[Solved]: How to use jQuery with Node.js with Examples

You can copy the files into your custom local directory. Alternatively, you can clone the entire project, navigate to the jQuery and AJAX implementation folder then install the packages.

git clone https://github.com/Stevealila/NodeJS.git
cd NodeJS/expressFormBody/jQueryAjax/
npm install

[Solved]: How to use jQuery with Node.js with Examples

Now let's jump into practical examples.

 

Example-1: How to use jQuery with Node.js server-side

Assume we want to change the h1 element's text content using jQuery on the server-side. Here are the steps to follow.

Open the jquery_server_side directory using a code editor and write the subsequent lines in the index.js file.

Advertisement

Step-1: Import jsdom

const jsdom = require('jsdom')

 

Step-2: Create the DOM

Let's create a DOM with the h1 element using the JSDOM() method of the jsdom module.

const dom = new jsdom.JSDOM("<h1> This is heading one </h1>")

 

Step-3: Import the jquery module and attach the window object to it

// create window object
const window = dom.window
// import jquery and attach the window object to it
const $ = require('jquery')(window)

Step-4: Use jQuery

Now we can apply jQuery. For example, let's change the text content of the above h1.

// Before changing text
const beforejQuery = window.document.querySelector('h1').textContent
console.log('before: ', beforejQuery)

// after modifying the text
$('h1').text('How to use jQuery with NodeJS')
const afterjQuery = window.document.querySelector('h1').textContent
console.log('after: ', afterjQuery)

We grab the h1 selector as we would on the client-side, then dissect and print its content on the console.

[Solved]: How to use jQuery with Node.js with Examples

Before changing the text with jQuery, it reads This is heading one. We then grab the same element with jQuery and change its text content using jQuery's text() method. The output then becomes How to use jQuery with Node.js.

user@hostname:-/jquery_server_side$ node index.js
before: This is heading one
after: How to use jQuery with Node.js

[Solved]: How to use jQuery with Node.js with Examples

That is the basics of generating the DOM and manipulating it with jQuery server-side. The main drawback of this method is that you have to customize jsdom further to exploit its full potential and that of jQuery.

That is why you could consider using jQuery on the frontend.

Advertisement

 

Example-2: jQuery on the client-side and Node.js on the server-side

Using jQuery on the frontend with Node.js on the backend mainly occurs through sending form data using jQuery and AJAX to an express web server's route.

Assume we want to collect username and email and send them to a web server for further manipulation. The web server, in return, sends an object bundling the manipulated data so we can update the UI with it.

We create a file structure as follows:

  • public folder: holds the frontend assets: index.html, style.css, frontend.js, and jq.js.
  • index.js file: web server implementation.
  • We pick the user details from index.html file, which links to two JavaScript files:
  • jq.js: contains compressed jQuery files.
  • frontend.js: implements jQuery AJAX.

We then send the username and email to the frontend.js file.

$(document).ready(function() {
    $('button').on('click', function() {
        $.ajax({
            type: "POST",
            url: "/registration",
            data: JSON.stringify({ username: $('#username').val(), email: $('#email').val() }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $('li').text(`${data.username} => ${data.email}`)
            },
            error: function (error) {
                console.log(error);
            }
        });
    })
})

The callback function packs the string username and email and then posts them to the /registration endpoint implemented in the index.js file.

[Solved]: How to use jQuery with Node.js with Examples

 

The script index.js file decodes the data through the express.json() method and sends it to the frontend where it is received through the jQuery AJAX callback function.

Advertisement
success: function (data) {
  $('li').text(`${data.username} => ${data.email}`)
},
error: function (error) {
  console.log(error);
}

The success object paints the DOM with the received data. Otherwise, it prints an error message.

[Solved]: How to use jQuery with Node.js with Examples

 

Conclusion

Understanding how to use jQuery with Node.js is straightforward after knowing how to generate and manipulate DOM on the server-side using jsdom and jquery modules, respectively. Alternatively, you can apply jQuery AJAX, as explained in this tutorial.

 

Related Keywords: node js jquery, nodejs jquery, jquery nodejs, node jquery, import jquery into js file, import jquery in js, require jquery

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

1 thought on “[Solved]: How to use jQuery with Node.js with Examples”

Leave a Comment

X