How do i react to xmlHttpRequest?

Hi, i have this in client:

var data = new FormData();
data.append("content", "hello");
var xhr = new XMLHttpRequest();
xhr.open("POST", "my-project.glitch.me");
xhr.send(data);

how do i set that if server receive “hello” then it send response “hi” to client?

also im not sure how do i get response from server…
i think its:

xhr.open("GET", "my-project.glitch.me")

im new to all this so sorry for stupid question

1 Like

This post was flagged by the community and is temporarily hidden.

1 Like

Hi! Welcome to the community!

There’s no such thing as a stupid question here :slight_smile:

Ok, first I will try to answer your question. XMLHttpRequest (XHR for short) is known to be a bit hard to work with, but I think what you need is like this:

var data = new FormData();
data.append("content", "hello");
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", handleResponse); // This is the new line
xhr.open("POST", "my-project.glitch.me");
xhr.send(data);

function handleResponse() {
  // In this function, 'this' is an XMLHttpRequest object
  // Do something with the response here
  console.log(this.status, this.responseText);
}

You attach a listener function before sending the request.

Above, we use this.responseText which should have the response data from the POST in it. But there are other properties you can check, to get the HTTP Status for example, and there’s a list here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties

Check out these docs on MDN: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Now, a lot of people swerve XHR altogether. A modern alternative is Fetch, which is built into most modern browsers as a replacement for XHR. Here’s a good intro to fetch: https://javascript.info/fetch

You can also use a library. In the old days, jQuery was popular for it’s ajax functions that do what you want. A more modern alternative is axios but adding it into your project is left up to you :slight_smile:

Hope this helps. Here to answer more questions when I can :slight_smile:

1 Like

Hello @azari :wave: Welcome to Glitch!

What you are trying to do is referred to as communication between a client and an API. Thus requires a front-end and a back-end.

I recommend you have a look at the Fetch API to send requests from the browser to a server. If your API returns JSON data I recommend you have a look at Axios, which I’ll be using in my examples below.

A simple example between a client-server relationship in code could look like this:

app.js (server-side)

// Import express
const express = require("express");

// Create an application
const app = express();

// Add a static site middleware. This allows
// the browser to request files like `index.html`
app.use(express.static(__dirname + "/public"));

// Add a ping route.
app.get(
  // This is the route of which the
  // browser can request a "pong"
  // response.
  "/ping",
  // This is the middleware used to respond
  // to the client, you can think of this
  // like the route handler.
  async (req, res) => {
    // Send a JSON response to the client.
    res.json("pong!");
  }
);

// Start your server.
app.listen(3000, () => console.log("🚀 Server is running at port 3000."));

client.js (client-side)

// A ping function to send a request to
// the ping route.
const ping = async () => {
  const { data } = await Axios.get("/ping");
  return data;
};

// Call the ping function:
ping()
  // Since the ping function
  // returns a promise we must
  // use .then() and .catch()
  // to get the responses.
  .then(data => console.log("Server said:", data))
  .catch(error => console.error("Server failed:", error));
1 Like

Axios needs to be included separately in the client side file (using a script tag) , right?

It can also be included using ES6 imports.