What is the best way to confirm the success of my post method using XMLHttpRequest?

I have limited experience with API's and recently wrote a function to send data to an API. I have bound this function to a textbox text change event, but I am unsure if it is working since I am not receiving any errors. Below is the code for the function:

function sendAPIData(url,introduction,coordinateid){
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "http://192.168.51.212:3368/casigo/sDAGinput",true);
    xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    var input = JSON.stringify({
      "coordinate": coordinateid,
      "url": url,
      "introduction": introduction
    });
    xhttp.send(input);
}

I expect this function to provide me with some input string.

Answer №1

One way to verify the server's response is by implementing a callback function:

function sendAPIRequest(url,intro,coordID) {
    var request = new XMLHttpRequest();
    request.open("POST", "http://192.168.51.212:3368/casigo/sDAGinput",true);
    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    var data = JSON.stringify({
      "coordinate": coordID,
      "url": url,
      "introduction": intro
    });

    // defining the callback function
    request.onload = function(response) {
      if (request.readyState === 4) {
        if (request.status === 200) {
          console.log("Server responded with success");
        } else {
          console.error("Error in server response");
        }
      }
    };

    request.send(data);
}

The request.onload function executes once the server responds to the XMLHttpRequest. The variable response holds the server's reply.

Answer №2

When working with the XMLHttpRequest object, developers can access the status and readyState properties to handle responses from the server using the onreadystatechange event. A code snippet like the one below demonstrates how this can be done.

xhttp.onreadystatechange=function(){
   //readyState == 4 means the request is done and a response is received from the server

   if (xhttp.readyState==4 && xhttp.status==200 && typeof(xhttp.responseText) == 'string'){
      //Do something          
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining Multiple Arrays into a Single Array

Is there a way to combine this merge operation that creates one array using forEach into a single array at the end? affProd.pipe(mergeMap( event1 => { return fireProd.pipe( map(event2 => { const fi ...

Tips for making jQuery maphilight function properly?

Can someone assist me with Mapilight? I have been trying to get it to work but no success so far. Here are the script links in the head section of my HTML. <script type="text/javascript" src="/js/jquery.js"></script> <script type="text/ja ...

Activating controllers with 2 independent sliders

(Using the WordPress Slider Revolution plugin) I have set up two sliders next to each other - one displaying the service name and description, and the other showing images. The goal is for clicking a specific bullet on the service slider to also trigger t ...

Issue with Web API and AJAX: Unable to retrieve resource, server returned status code 400

[HttpPost("Login")] public async Task<IActionResult> Login([FromBody] SigninViewModel formData) { MemberCredential membercredential = await db.MemberCredential.FirstOrDefaultAsync(t => t.MemberAccount.Equals(f ...

What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks. Everything is functioning smoot ...

Having trouble displaying Google Map using GMapPanel in EXTJS 4?

Ext.Loader.setPath('Ext.ux', '../ux'); Ext.require([ 'Ext.tree.*', 'Ext.data.*', 'Ext.window.MessageBox', 'Ext.window.*', 'Ext.ux.GMapPanel' ]); var map = new Ext.ux ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

The setState function in React Native seems to be having trouble updating

I've been attempting to access state from a component, but for some reason, I'm not seeing any changes when I use setState(). Here is the current state of my component: class MyTestComponent extends React.Component { constructor(props){ ...

Limiting the number of characters in a textarea using React with TypeScript

Having encountered two issues, I've developed a textarea component that not only allows users to input text but also keeps track of the number of characters they have typed. First Issue: I'm attempting to check if the length of the current input ...

Generating entities with titles that are saved in the configuration document

Currently, I am in the process of developing a program that is designed to create objects based on the handlers specified in a configuration file. These objects will then be passed to a method within another class. The configuration file contains a list o ...

Understanding variable scope in Node.js routing with Javascript

Consider the following code snippet: app.get("/location1", function(req, res){ async_function().then(result => { var str = result.toString(); }).catch(...)..... }); There are variables defined inside the .then() block of the asynchronous ...

Unable to reach the third tier of JSON data for this specific ID

Having trouble accessing the ID of a booking in my flatlist keyExtractor when loading data from a JSON API. This is causing nothing to show up in my flatlist. JSON data: { "success": true, "data": { "bookings": ...

The Angular Element's emitted number transforms into a string once it reaches the JavaScript event listener

Within my Angular Elements web component, I have defined and emitted events in the following way: @Input() groupId: number = -1; @Output('group_change') groupChange!: EventEmitter<number>; ... this.groupChange.emit(groupId); I integrated ...

Response Listener in Android Studio is a powerful tool used to

I've been encountering a java.lang.String cannot be converted to JSONObject error in my code. Interestingly, my friend has no issues running the exact same code on the emulator. public class LoginActivity extends AppCompatActivity { @Override protec ...

Receiving successful ajax responses and populating text fields with the returned values

I have been attempting to populate the values from an AJAX success response into their corresponding fields, but I am encountering some difficulties. Despite receiving the desired data in the "alert(responseObject)" within the success section, I am unable ...

Using jQuery to animate a form submission in CodeIgniter

I have integrated two jQuery plugins into my application, which are: jQuery validate : . jQuery blockui : http://malsup.com/jquery/block/#download The application is developed using PHP Codeigniter and jQuery. It consists of a form created with the fol ...

When attempting to send a request for the JSON body to Node.js using the await fetch method, I encountered an issue

Recently, I started working with node js and attempted to fetch JSON data using the code below: const req = await fetch( "http://localhost:3000/api/auth/signin", { method: "POST", header:{ 'Accept':&apo ...

What are some alternative ways to refactor my code in AsyncTask without using runOnUiThread?

Greetings to all Android developers! I am facing an issue with the compatibility of my old code and API 18. All the codes below work perfectly on Android 2.3. However, when I attempt to run them on a newer API version, it results in a crash. Is there a w ...

Utilize jQuery for parsing JSON data

Asking for help here because I am struggling with a seemingly simple task. Here is the JSON data that's causing me trouble: {"name":"cust_num","comparison":"starts_with","value":"01"}, {"name":"cust_name","comparison":"starts_with","value":"ad"}, {"n ...

Ways to verify the presence of users in the Database

I have successfully retrieved the data with the code below, but I am encountering issues with my script's if and else statements. Any tips or advice on how to improve this functionality? server.post('/like', (req, res,next) => { var ...