Let's now learn how to send data to a server in an AJAX request. The server will do something with this data and send back the result to us.
Our test server will process data
sent to /handler/
:
button.addEventListener('click', function() {
let promise = fetch('/handler/');
});
First, let's send a GET request:
button.addEventListener('click', function() {
let promise = fetch('/handler/?num=3');
});
Let's get the sent data on the server side:
export default {
'/handler/': function({get}) {
console.log(get.num); // shows 3
}
}
Let's do something with this data and send it back:
export default {
'/handler/': function({get}) {
return get.num ** 2;
}
}
On the client side, we get the result and output it somewhere:
button.addEventListener('click', function() {
fetch('/handler/?num=3').then(
response => {
return response.text();
}
).then(
text => {
console.log(text);
}
);
});
On the client side, a div and a button are given. On button click, send two numbers to a server. Let the server find the sum of the passed numbers. Write the result in the div.
Let an array be given on a server. Let the server wait a number passed as a parameter and return an array element corresponding to that number. On clicking the button, send some number to the server, and display the server's response in a paragraph.