Hey Sammy!

Sammy.js is an efficient and tiny library for manipulating the DOM and is still used by developers who look to make the web interaction fast and smooth. It has many advantages over other libraries such as jQuery. This article will take a look at what Sammy offers and how to utilize this powerful library in your next project.

In this article, I will show you how to perform routing with jquery using the Sammy JavaScript framework.

Before moving on to the front end and sammy.js. Let’s create our server using Node js and for the database, we will be using Mysql.

Step 1: Creating the Application

make a server directory using terminal

mkdir server

Go to the root folder of your application and type npm init to initialize your app with a package.json file.

cd server
npm init

Step 2 :Install the dependencies

npm install express body-parser cors mysql2 sequelize--save

Sequelize needs the MySql module installed in your project. if you have not installed the MySql module then make sure before installing Sequelize you need to install the MySql2 module.

Step 3:Setting up our web server

Create a new file named server.js in the root folder of the application with the following contents –

const express = require('express');
const cors = require('cors')

// create express app
const app = express();

// parse requests of content-type - application/json
app.use(express.json())

//allows browser client to interact with resources from a different //origin
app.use(cors());

app.get('/', function (req, res) {
    res.send('<html><body><h1>Server is working</h1></body></html>');
});

// listen for requests
app.listen(3000, () => {
    console.log("Server is listening on port 3000");
});

Now to run the server we can write node server.js in the terminal.

$ node server.js 
Server is listening on port 3000

go to http://localhost:3000 to access the route we just defined.

Step 4:Configuring and Connecting to the database

make a new file and name it database.js

const Sequelize = require('sequelize');

const sequelize = new Sequelize('dbName', 'username', 'password', {
    host: 'localhost',
    dialect: 'mysql',
});

change the dbName with your database name, username with your username (default is root), and password with your password.

Now, to authenticate the connection-

sequelize.authenticate()
    .then(() => {
        console.log('Connection done.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

Step 5:Define student model

create a model.js file and define a model

module.exports = (sequelize,Sequelize)=>{
    const students = sequelize.define('students', {
        firstName: {
            type: Sequelize.STRING,
            field: 'firstName'
        },
        lastName: {
            type: Sequelize.STRING,
            field: 'lastName'
        },
        email: {
            type: Sequelize.STRING,
            field: 'email'
        },
        
    }
    );
    return students;
}

Here, we have created a very basic model with fields of student’s firstName, lastName, and email.

Now, let’s import this model file into the databse.js

const db = {};

db.students= require('../server/model.js')(sequelize, Sequelize);

sequelize.sync({ force: false })
    .then(() => {
        console.log(`Database & tables created!`);
    });

module.exports.students= db.students;

We have successfully created our table in our database.

Step 6: Writing database queries

Let’s create a query.js file where we will write all our database related queries

const db = require('../server/dataBase');

const students= db.students;

Now, come back to the server.js file and write the required routes

let’s start with post student details first

const studentQuery = require('../server/query.js');

app.post('/student', function (req, res) {
    studentQuery.addStudent(req.body.firstName, req.body.lastName, req.body.email)
    res.status(200).json('Added Successfully');
});

Here, we are calling addStudent function in the query.js file but currently, it doesn’t exist. So let’s write the function

module.exports.addStudent = async (firstName, lastName, email) => {
    return await students.create(
        {
            firstName: firstName,
            lastName: lastName,
            email: email,
        }
    );
}

similarly, we will create functions for getting all the data, getting specific data updating and deleting data

module.exports.getAllStudentData = async () => {
    let studentData = await students.findAll();
    return studentData ;
}
module.exports.getStudentData = async (id) => {
    let studentData = await students.findByPk(id);
    return studentData ;
}
module.exports.updateStudentData = async (id, firstName, lastName, email) => {
    let studentData = await students.update({
        firstName: firstName,
        lastName: lastName,
        email: email,
    },{where:{id:id}});
    return studentData ;
}
module.exports.deleteStudent = async (id)=>{
    return await students.destroy({
          where:{id:id}
      })
      
  }

Now, move back to server.js and write the remaining routes

Step 7: Creating routes

app.get('/list', async function (req, res) {
    let data = await studentQuery.getAllStudentData();
    res.status(200).send(data);
});

app.get("/student/:id", async function (req, res){
    let data = await studentQuery.getStudentData(req.params.id);
    res.status(200).send(data);
})
app.put("/student/:id", async function (req, res){
    await studentQuery.updateStudentData(req.params.id, req.body.firstName, req.body.lastName, req.body.email)
})

app.delete('/delete', async function (req, res) {
    await studentQuery.deleteStudent(req.body.id);
    let data = "Student\'s Data deleted successfully!"
    res.status(200).send(data);
})

We have successfully created our web server! Now start the server and let’s move to our frontend

Step 1: Initial Page Layout

I will design the index.html page and use bootstrap for my designs. I will import bootstrap, sammy, and jquery on the page.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script type="text/javascript" src="scripts/jquery.js"></script>
    <script src="scripts/sammy.js"></script>
    <script src="script.js"></script>
    <link rel="stylesheet" href="scripts/bootstrap.css">
    <title>Sammy js Routing</title>

</head>

I will define two pages, one that displays a list of students and another page with a form for adding new students’ details. I will add the code to display the list of students on an index.html page and place a button on this page that links to the form-adding page.

I have also added a <div> for the page after routing and set its <id> to content.

<body>
    <div class="container">
        <div class="jumbotron " style="background-color: #AEC6CF;">
            <div class="row">
                <div class="col-md-6">
                    <a href="#/add" class=" btn btn-success">Add Student</a>
                </div>
                <div class="col-md-6  text-right">
                    <a href="#/list" class=" btn btn-success" id = "list">Student List</a>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div id="content"></div>
            </div>
        </div>
    </div>
</body>

Step 2: Routing operations

Now to use sammy we will create a script file, and create an app

var app = $.sammy(function () {
});

To start the code with a specific page, we need to use the run() function.

app.run('#/');

The id of the field to be routed is determined by the this.element_selector command.

this.element_selector = '#content'

By this, I have specified the area to be redirected on the index.html page is where it is defined <div id = "content">.

Now, how do we perform routing?

this.get('#/add', function(context) { context.$element().append('<h1>Hello World</h1>'); });

The this.get() function can perform routing for us.

Here the first parameter is where we define the routing name. This name will be used for index.html <a href=”#/routing”>.

And in the second parameter, we determine the operation to be done as a routing result. Represents the <div> tag to be redirected by $element(). With append() function we will write routing operations to the post-routing screen.

So now, when we click on Add Student button it shows Hello World in the content div.

Step 3: Add Student page

Let’s start with the addStudent.html structure

<form id="formSubmit">
    <div class="form-group">
        <input type="text" class="form-control" id="inputName" placeholder="Enter name" \>
    </div>
    <div class="form-group">
        <input type="text" class="form-control" id="inputSurname" placeholder="Enter surname" \>
    </div>
    <div class="form-group">
        <input type="text" class="form-control" id="inputMail" placeholder="Enter e-mail" \>
    </div>
    <div class="form-group">
        <input type="button" class="btn btn-primary" id="btnAdd" value="Save" />
    </div>
</form>

Here, we created a simple form with 3 fields and a save button

The load() function enables us to interact with the Html elements on the page. To do this, we need to pass a callback function as an argument to the load() function. 

Now we will change the this.get(#add) part

this.get('#/add', function (context) {
            context.$element().load('addStudent.html', function () {
                $('#btnAdd').click(addOrUpdateStudent)
            });
        });

On click of the add student button addStudent.html will be loaded and after the user fills the form and clicks on the save button addOrUpdateStudent function will be called.

function addOrUpdateStudent() {
    var student= {
        firstName: $('#inputName').val(),
        lastName: $('#inputSurname').val(),
        email: $('#inputMail').val()
    }
    $.ajax({
        url: "http://localhost:3000/student",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(student),
        success: function () {
              alert("Student data added successfully")
           }
        })
    }
}

We made a student object with the input values and using ajax we are hitting a post request to our server

On success, it will show an alert with the “Student data added successfully” message.

Step 3: Student Listing page

To create a list of students, let’s design the listStudent.html page. I will use the <ul> and <li> tags to make lists.

<div>
    <ul class="list-group">
       
    </ul>
</div>

We will use the this.get method again but this time our route is #/list and we will load listStudent.html

this.get('#/list', function (context) {
            context.$element().load('listStudent.html', function () {
                
            });
        });

Now to load the data we have added we will use ajax and get all the data from our database

 $.ajax({
        url: "http://localhost:3000/list",
        type: 'GET',
        success: function (data) {
            for (let index = 0; index < data.length; index++) {
             $('ul').append('<li class="list-group-item"><div class="row"><div class="col">' +
             data[index].firstName + '</div><div class="col">' +
             data[index].lastName + '</div><div class="col">' +
             data[index].id + '</div><div class="col">' +
             data[index].email + '</div>'
             </li>`
            );
           }
         }
        })

Using for loop I have displayed all the data separately with the help of div tags

We have successfully finished Create and Read part of the CRUD, now moving on to edit and delete.

Step 3: Add the edit and delete button to the list items

+ `<div class="col ">
<a href="#/add/${data[index].id} "class="btn btn-primary" id="btnEdt">edit</a> &nbsp;`
 + `<input type="button" onclick="deleteStudent(${data[index].id})"class="btn btn-primary" id="btnDel" value="Delete" />
</div>
</div>

On click of edit button, it will redirect to route #/add/<id of the selected student>

and on click of delete button deleteStudent(<id of the selected student>) function will be called

Let’s work on the delete function first

Step 4: Delete Student

function deleteStudent(id) {
    $.ajax({
        url: "http://localhost:3000/delete",
        type: 'DELETE',
        data: JSON.stringify({ "id": id }),
        contentType: 'application/json',
        success: function (data) {
            alert("Student data deleted successfully")
            location.reload();
        }
    })
}

Here we are hitting the server using ajax with DELETE method and we are sending the id of the selected student.

On success, it will show an alert message “Student data deleted successfully”

Step 5: Edit Student

On click of the edit button, it redirects #add/id, so we will need to write a this.get() function for this route

this.get('#/add/:id', function (context) {
            context.$element().load('addStudent.html', function () {
                $.ajax({
                    url: "http://localhost:3000/student/" + location.hash.substring(6),
                    type: 'GET',
                    contentType: 'application/json',
                    success: function (data) {                        
                        $('#inputName').val(data.firstName)
                        $('#inputSurname').val(data.lastName)
                        $('#inputMail').val(data.email)
                    }
                })

                $('#btnAdd').click(addOrUpdateStudent)
            });
        });

    });

This function will load the addStudent.html and we used ajax to get the input values of the student, we are using location.hash.substring(6) to get the id from the URL and send it to the server.

And on the click of the save button, it will call the addOrUpdateStudent function, So lets first update the function

function addOrUpdateStudent() {
   
    var student= {
        firstName: $('#inputName').val(),
        lastName: $('#inputSurname').val(),
        email: $('#inputMail').val()
    }

    let id = location.hash.substring(6);
    
    if (!id) {
        $.ajax({
            url: "http://localhost:3000/student",
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(student),
            success: function (data) {                
                alert("Student data added successfully")
            }
        })
    }
    else {
        $.ajax({
            url: "http://localhost:3000/student/" + id,
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(student),
            success: function (data) {
                console.log("Student updated successfully!")
            }
        })
    }
}

Now if id exists then update will work or else add will work.

For update, we have used ajax with the PUT method and we have sent the new details of the existing student. On success alert, a message will pop up.

Congratulations! You have successfully created a CRUD app using Sammy, Nodejs, and MySQL!