DEV Community

Raj Madisetti
Raj Madisetti

Posted on

Using AJAX in Conjunction with MongoDB

Hello fellow Javascript coders,

In this article, we will be discussing how to implement AJAX calls into your full-stack web application that incorporates a MongoDB database.

First of all, AJAX is a method in jQuery that allows a program to send and receive data from a server (i.e. MongoDB) simultaneously without even refreshing the page. Thus, AJAX is very important for implementing applications with buttons or input from the user since it can be used in functions that are responsible for rendering text or data to the page.

Next, let's implement AJAX into an application. We need to require all of the relevant packages in the server.js or a differently named file that connects the mongoose database to your api and html routes. The file should look similar to this:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const PORT = process.env.PORT || 3000; // any port number is acceptable

// Initialize Express
const app = express();

// Use body-parser for handling form submissions
app.use(bodyParser.urlencoded({ extended: true }));
// Use express.static to serve the public folder as a static directory
app.use(express.static('public'));

mongoose.connect('mongodb://localhost/[name of application database]', { useNewUrlParser: true });

// Routes
// API Routes (require from routes folder and pass in Express app)
require('./routes/api-routes')(app);
// HTML Routes (require from routes folder and pass in Express app)
require('./routes/html-routes')(app);

// Start the server
app.listen(PORT, function() {
console.log(App running on port ${PORT});
});

Now, the preliminary packages are required if they weren't already. Next in a different js file, you can create functions that accesses your mongoose routes such as GET, POST, or DELETE using AJAX. Here is an example of how to formulate a render function that gets data from a mongoose database and displays it to the page:

const render = function () {
$.ajax({ url: '/[put your route here]', method: 'GET' })
.then(function (data) {
let htmlstr = '';
data.forEach(element => {
htmlstr +=<h1 class="content">${element.content}</h1>;
});
$('#addStr').html(htmlstr);
})

.catch(function (err) {
console.log(err);
});
}

In this function, the AJAX call is using the databases GET routes and, for each data entry, it creates an html h1 element with the contents of the entry and adds it to an empty div.

Top comments (0)