Languages
[Edit]
EN

React - Ajax POST request

3 points
Created by:
FryerTuck
649

In this article we would like to show you how to make AJAX POST request in React.

In below example fetch method were used with two parameters:

  • path to backend logic located on server,
  • request configuration that let us to configure: request method, request headers, request body, etc.

In below example we used POST method that alows to send some data in body.

Practical example:

// ONLINE-RUNNER:browser;

//import React from 'react';

const Form = () => {
  const handleSubmit = async (e) => {
    e.preventDefault();
    const elements = e.target.elements;
    const requestData = {
      username: elements.username.value,
      password: elements.password.value,
    };
    const requestJson = JSON.stringify(requestData);
    try {
      const response = await fetch("/path/to/backend", {
        method: "POST",
        body: requestJson,
      });
      const responseText = await response.text();
      console.log(responseText);
    } catch (ex) {
      console.error("POST error!");
    }
  };
  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Username: </label>
        <input type="text" name="username" />
      </div>
      <div>
        <label>Password: </label>
        <input type="password" name="password" />
      </div>
      <div>
        <input type="submit" value="Submit!" />
      </div>
    </form>
  );
};

const root = document.querySelector("#root");
ReactDOM.render(<Form />, root);
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - Ajax POST request
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join