Performing an Ajax POST request in plain JavaScript without utilizing the jQuery

I am looking to retrieve a JSON object from the server side via an URL that needs to be created on the client side (using JavaScript) using an ajax POST request.

var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.responseType = "json";
oReq.onload = function(e) {
    var jsonObj = oReq.response;
   /* ... */
}

What should be implemented inside the function(e) in this scenario?

Note that I am avoiding the use of jQuery for this task.

Answer №1

Make sure to execute the send() function for your request to go through.

For a helpful example, take a look at this slightly modified version:

var requestedData = new XMLHttpRequest();

requestedData.open("POST", url, true);
requestedData.responseType = "json";
requestedData.onload = function(e) {
  var jsonDataResponse = requestedData.response; // not responseText
  /* ... */
}
requestedData.send();

Answer №2

Below is a function I created and frequently use for handling ajax requests, posts, and more

 function ajax(url, callback, type, data, uploadProgress, progress){
  // url,callback,type(get),FormData(null),uploadProgress,progress 
  let xhr = new XMLHttpRequest;
  !uploadProgress||(xhr.upload.onprogress=uploadProgress);
  !progress||(xhr.onprogress=progress);
  xhr.onload = callback;
  xhr.open(type || 'get', url);
  xhr.send(data || null);
 }

It seems that only Chrome supports the responseType='json';. If you remove it, you can retrieve the JSON response using

JSON.parse()

For example:

JSON.parse(xhr.response)

To access the response from this ajax call, there are 3 options to choose from

1. In your case or mine:

xhr.response
//or yours
xhr.response

2. Using this:

this.response 

3. Event target:

event.target.response

Description of the ajax function:

This ajax function takes in 6 parameters: url, callback, type (get or post), FormData (or null), uploadProgress, progress.

Only url and callback are required for a simple GET request.

ajax('url',function(){console.log(this.response)})
// It's better to use a function reference to avoid memory leaks
// like
function cb(){console.log(this.response)};
ajax('url',cb)

In the case of a POST request, you need 4 parameters:

url, callback, type(post in your case), and formdata.

So:

ajax('url', callbackFunction, 'post', fd);

Where fd can be constructed in 2 ways:

var fd = new FormData();
fd.append('key', 'value');
ajax('url', callbackFunction, 'post', fd);

Alternatively, you can also submit the entire form

var fd = new FormData(document.getElementsByTagName('form')[0]);
ajax('url', callbackFunction, 'post', fd);

You can also add a progress event function if needed

function progress(e){
 console.log(e.loaded/e.total*100)
}

Same goes for the upload progress

The callback function can look like this

function callbackFunction(e){
    console.log(e.target.response);
    console.log(this.response);
    console.log(xhr.response);

    // Without responseType

    console.log(JSON.parse(e.target.response));
    console.log(JSON.parse(this.response));
    console.log(JSON.parse(xhr.response))
}

If you have any questions feel free to ask.

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

Initiating a dual XMLHttpRequest operation

Embarking on my initial AJAX project, I am delving into the realm of crafting a dual AJAX function. The primary goal is to utilize the output string ("venue_ID") of the first function as an input for the second AJAX function in order to generate a string ( ...

Using ajax and jQuery to upload images before submitting a form on the MVC platform

I am looking to create a form within my MVC application with input fields. Additionally, I want users to be able to upload images from their hard drive asynchronously by selecting an image and clicking an upload button. After a successful upload, the contr ...

Angular JS form cloning feature

I'm facing a challenge in creating a dynamic form with multiple sections. At the end of the form, I want to include a "Add New Form" button which will duplicate the existing form below it, each with its own save button. What's the most effective ...

Testing Events in Redux using Mocha

I have been developing a React component that consists of a field and a Submit button. The event 'onMapPointAdded' is triggered when users enter text and click the Submit button. I am looking for guidance on how to test this functionality. Any ...

What is the best way to add an array into another array?

I am working with a main array consisting of 64 positions, and for each position, I need to create another array. For example: someArray[index] = [someObject]. How can I generate these arrays? And how can I access someObject.name and someObject.lastName f ...

Updating a MongoDB document using only the data from checked checkboxes

Imagine having data structured like this: _id:60e2edf7014df85fd8b6e073 routineName:"test" username: "tester" monday:[{ _id: 60e430d45395d73bf41c7be8 exercise: "a" }{ _id: 60e4329592e ...

Exploring the world of Leaflet. Have you ever encountered situations where adding a variable name to the GeoJSON file is crucial

Currently, I am in the process of learning Leaflet, JavaScript, and more. To test my understanding, I am using code examples from the Leaflet website and making modifications for my own purposes. However, I have noticed that in all the examples I have co ...

Remove elements from an array in Typescript if they are not present in a nested array

I am struggling with filtering values from a single-dimensional array based on id matches in an array of objects. array1 = [1, 3, 15, 16, 18]; array2 = [ { id: 1, dinner : pizza }, { id: 15, dinner : sushi }, { id: 18, dinner : hummu ...

Load prior state when the value changes with UseState in NextJS

In the development of my e-commerce application, I am currently working on implementing filters based on category and price for the Shop page. To handle this functionality, I have established the initial state as follows: const [filters, setFilters] = useS ...

Removing quotation marks from a string stored as a parameter in the MongoDB Java driver

I am currently working with the MongoDB Java driver and I have a code snippet that looks like this: doc = new BasicDBObject("Physicalentity", "Pressure"). append("Sensor", "Tinkerforge"). append("Unit", "Lux"). append("loc", Location). append("value", p ...

What is the best way to fetch all the orders from my product schema using response.send?

This is my custom Product schema const productSchema = new mongoose.Schema({ title: { type: String, required: [true, "Title is required"] }, details: { type: String, required: [true, "Details are r ...

jQuery tipsy not triggering click event in Internet Explorer

Hey there! I've been using the jquery tipsy plugin for displaying colour names above colour swatch images. One thing I'm trying to do is trigger a checkbox to be checked/unchecked when a user clicks on the image. $(document).ready(function(){ ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...

Unable to access this context in Firefox debugger after promise is returned

I'm curious as to why the 'this' object is not showing up in the debugger in Firefox, but it does appear in Chrome's debugger. When I try to access 'this.myProperty', it shows as undefined. This is the code from my TypeScript ...

Removing a value from an array contained within an object

I have a scenario in my task management application where I want to remove completed tasks from the MongoDB database when a logged-in user marks them as done. Below is the snippet of code for my Schema. const user = new mongoose.Schema({ username : Str ...

Connect the AngularJS data model with a Foundation checkbox element

I am attempting to link a model (a boolean value) to a checkbox created with Foundation (Zurb). I have created a small demonstration displaying the issue: http://jsfiddle.net/JmZes/53/ One approach could involve simply creating a function that triggers o ...

Extract information from an HTML table into PHP

I have an HTML table that is generated dynamically and I am looking to extract the data from it using the POST method. Is there a way to accomplish this? Are there any alternative methods you would suggest for achieving this goal? Below is a basic example ...

Strategies for sending data in the body of a GET request in a React.js API

I'm having an issue passing data in the body of a GET type API request in my React.js app. Here is the code I am using, but the API isn't receiving any data. getUnits = ( key, text, code, limit, offset ) => { let data = JSON.st ...

Unable to verify serde: org.openx.data.jsonserde.jsonserde

I am facing an issue while trying to create a table on hive. My original data is in json format, so I have downloaded and built serde as well as added all the required jar files for it to function properly. However, I keep encountering the following error: ...

Manipulate numerous documents within MongoDB by updating them with varying data in each

I have a list of unique IDs: idList = ["5ec42446347f396fc3d86a3d", "5ec422d4347f396fc3d86a3c", "5ecefaf0aead3070fbdab7dd"] I want to update the documents that match these IDs with different data in each one: const currentData = await Data.updateMany( ...