ajax in javascript

To make an AJAX request in JavaScript, you can use the XMLHttpRequest object (also known as xhr). Here's an example:

index.tsx
let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};

xhr.open('GET', 'url_here');

xhr.send();
208 chars
12 lines

In this example, we create a new instance of XMLHttpRequest and set up an event listener for when the request state changes. When the request state is 4 (completed) and the status is 200 (success), we log the response text to the console.

We then open the request (GET or POST) and specify the URL to send the request to. Finally, we send the request.

You can also pass data in the request by using the send method:

index.tsx
xhr.send('name=value&name2=value2');
37 chars
2 lines

This will send the data in the format of 'name=value&name2=value2'. You can also pass JSON data by using the JSON.stringify method:

index.tsx
let data = {name: 'John', age: 30};
xhr.send(JSON.stringify(data));
68 chars
3 lines

Note that using AJAX requires knowledge of server-side programming as well in order to handle the incoming requests and send back responses.

gistlibby LogSnag