How to send data via AJAX in React
Asynchronous JavaScript and XML (AJAX) is used in web applications to allow us to communicate with the server or API without needing constant page loading. It makes the web page more interactive and dynamic because we can update specific parts of the page asynchronously without interrupting the user's experience.
To send data via AJAX in a React application, we can use the axios library and fetch API. Let's discuss them.
Using axios library
Axios is a popular JavaScript library that provides an easy-to-use interface to send HTTP requests to a web browser.
Installation
To use axios in the web application, we have to install it first.
If the project is created using
npmornpx, we will run the following command:
npm install axios
If the project is created using
yarn, we will run the following command:
yarn add axios
Syntax
Whenever we send data through axios we use the post request. The axios.post() function takes two arguments: the url parameter that specifies the URL where the request is sent, and the data parameter that contains the data to be sent. We use the await keyword to wait for the response from the API before proceeding with the execution of the code. The response refers to the message sent by the API after receiving the HTTP request.
const response = await axios.post(url, data);
Coding example
The following example demonstrates how we can send data via AJAX using the axios's post method.
import React from 'react';
import DataSender from './DataSender';
const App = () => {
return (
<div>
<h1>Welcome to Educative</h1>
<DataSender />
</div>
);
};
export default App;
Let's understand what happens in DataSender.js file:
Line 1: We import
Reactlibrary and theuseStatehook from thereactpackage.Line 4: We declare a functional component named
DataSender.Lines 5–6: We define two
useStatehooks. We use the first oneinputNameto store the input name of the form and the second onemessageto store our display message based on the request status.Line 9: We declare an asynchronous function
handleSubmitwhich is called when the form submits.Line 10: We call the
preventDefaultfunction to prevent our page from refreshing after the request.Lines 13–15: We create a data object with a
nameproperty. This property is assigned the value of theinputNamestate variable.Line 19: We use the
axios.postmethod to send ourdataobject to the API and store the response of the API in a variableresponse.Lines 22–26: If the request is successful, the response has a status value of
201and set the value ofmessageto'Data sent successfully!'. Otherwise, set the value ofmessageto'Failed to send data.'.Lines 27–29: We display the
errorif we encounter any.Lines 33–42: We create a form with an input field where we enter the name, a button to submit the form, and a paragraph to display a response message received from the API.
Let's discuss another way of AJAX: using fetch API to send data in React.
Using fetch API
Fetch API is a JavaScript feature used to make AJAX requests and share data between client-side code and a server or API without using any external libraries.
Syntax
Whenever we send data through fetch API, we call the fetch function and pass the URL of the server we want to send messages to. The response refers to the message sent by the server after receiving the HTTP request.
fetch(URL).then(response => {//Handle the response from the server}).catch(error => {//Handle the errors here});
Coding example
The following example demonstrates how to send data using fetch in AJAX.
import React from 'react';
import DataSender from './DataSender';
const App = () => {
return (
<div>
<h1>Welcome to Educative</h1>
<DataSender />
</div>
);
};
export default App;
Let's discuss fetch method from the above code executable.
Lines 16–22: We use the
fetchmethod to senddataobject to the API and store the response of the API in a variableresponse. Along with this, we set the request method toPOSTand theContent-Typeheader specifies the type of data format being sent. In our case, we set'application/json', meaning we will send data inJSONformat. After it, we convert our data intoJSONformat using theJSON.stringify()function.Lines 25–29: If the request is successful, the
response.okreturnstrueand we set the value ofmessageto'Data sent successfully!'. Otherwise, we set the value ofmessageto'Failed to send data.'.
Free Resources