AJAX & JSON Explained | Examples

Video Tutorial

Overview

So whether you are a new web developer or you want to know how asynchronous requests are made (AJAX) and also work with JSON.

Actually AJAX is a request/response technique used to send data from the client side to the server side where the server can handle the sent data and return a response (with data if needed), as simple as that this is the main workflow of AJAX, and JSON comes in handy when sending the data so it is easy to parse and to manipulate during that process that’s why they are used in the process together, you can use other types of data rather than JSON but still JSON the best choice.

So let us dive into a quick example of how can we send a request and receive a response, consider watching the video tutorial above for more detailed information.

AJAX and JSON

We are going to use Jquery for the AJAX request/response, so make sure to include jquery on your project, if you don’t know what is Jquery you can check more about it here

start by setting up an HTML file an link it with your javascript file so we are going to use for Ajax, and set up a server, I’m using node JS for creating the server and routing, check express for more detailed instructions.

here is our server set up

//Require Express and Path Modules
const express = require('express');
const app = express();

const path = require('path');

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

//Use JSON Body Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(__dirname + "/dist"));

//Index Page Send HTML File
app.get('/', (req, res) => {
    res.sendFile(path.resolve('dist/index.html'));
});

//Listen ON PORT 3000
app.listen(3000, () => {
    console.log('Server Running 3000');
});

Server Running at: [http://localhost:3000](http://localhost:3000)

After running the server

# our server file is called main.js 
node main.js

you can access the server on http://localhost:3000

Now the Our Server is set up and running, so we can send our ajax requests

Make sure to add the Route Listener for a POST request, because we are going to send an AJAX POST Request, so add this lines to your server code and restart the server

//POST Request ROUTE
app.post('/ajax-request', (req, res) => {
    let data = 'ACCESS DENIEDED!';
     // req.body.action the data sent using AJAX Request, so we are retreiving it and do some checking 
    if (req.body.action == "getTodos")
        data = myTodos;
    //Here we are sending a Response Back (JSON)
    res.send({ todos: data, paramaters: req.body.action });
});

All we left us is to send the request, so go into your javascript file (the one linked with your HTML Page) and send an AJAX Request using Jquery, we send the request on a button click

//We are going to send the request on a Button Click 
$ajaxBtn.on("click", (e) => {
    //Ajax Request  using Jquery
    $.ajax({
        url: "/ajax-request", ///< The TARGET URL (the one we setted up in the server route) 
        type: "POST", ///< The type of the request (GET, POST...)
        dataType: "json", ///< Response DATA Type (Any other data types)
        data: { action: "getTodos" }, ///< The Data we are going to Send
        success: (result) => { ///< Trigerred On Success Request/Response
            //Do anything with the received data
            console.log("AJAX SUCCESS ", result);
        },
        error: (error) => { ///< Trigerred on HTTP Error or any other server ERROR
            console.log("AJAX ERROR ", error); 
        }
    });
});

Now refreshing the page, and pressing a button should send the request and receive the List of todos from the Server (Most of the time the server gonna need to retrieve the data from the database), and console log the todos, as simple as that.

so it is very simple actually to send and receive Data between the Client and the Server using AJAX and JSON for storing data.

Consider Practising AJAX by doing more real-world examples.

No Comments Yet