How to send dynamic data using Ajax?


This page explains how send dynamic data using Ajax / JavaScript. We assume data are in an HTML form, when the user click the Submit button, data are send using Ajax.

HTML form

First, we need an HTML form. If the reader is not familiar with HTML forms, I recommand reading this online and free web development course. Our form has two fields, one for the firstname, one for the lastname:

<form id="form">
  <input type="text" id="firstname" name="firstname" value="John"><br><br>
  <input type="text" id="lastname" name="lastname" value="Smith"><br><br>
  <input type="submit" value="Submit">

We also add a division for displaying the response from the server after the Ajax query:

<div id="output"></div>

Here is the final interface:


To get the data posted by the form, we have to trigger an event when the form is submitted:

// Trigger an event when the form is submitted
const form = document.getElementById('form');
form.addEventListener('submit', (event) => {

    // Do some awesome stuff here when the form is submitted
    // ...

    // Prevent HTML posting form by the browser (i.e. default behavior)

We can obtain the data from each field with the following lines:

let firstname = document.getElementById('firstname').value;
let lastname = document.getElementById('lastname').value;

The response is copied the division dedicated to the server response. Let's prepare the output object:

const output = document.getElementById('output');

For AJAX query, we use the JS Ajax Module presented and explained on this page. We query the Rest API at This demo API reply data posted in JSON.

.post({ "firstname": firstname, "lastname": lastname})
.then(function (response) { output.textContent = response })
.catch(function(failure) { alert ('Error') })

The first above line call the ajax() method with the URL of the rest API. The second line specify parameters and send the query If the request success, the callback function in the then() clause will be called. Here, received data are displayed in the response division. If the request failed, the error will be catched. Here, an error message is displayed in an alert.

Here is the final result:

See also

Last update : 11/09/2022