Exploring how to integrate a jQuery ajax request within Javascript's XmlHttpRequest technique

My current setup involves an ajax call structured like this:

var data = {"name":"John Doe"} $.ajax({ dataType : "jsonp", contentType: "application/json; charset=utf-8", data : JSON.stringify(data), success : function(result) { alert(result.success); // result is an object which is created from the returned JSON }, });

However, I am now looking to convert it into JavaScript's XmlHttpRequest. I understand the basic syntax, but I am unsure how to specifically translate this jQuery ajax functionality into XmlHttpRequest.

In particular, I am seeking guidance on how to specify the dataType when using XmlHttpRequest.

Answer №1

Here is an example of how you could achieve this:

let xmlhttp = new XMLHttpRequest();
let url = "request/url";
let data = {"name":"John Doe"};

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        let myArr = JSON.parse(this.responseText);
        successCallback(myArr);
    }
};
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8")
xmlhttp.responseType = "json";
xmlhttp.open("POST", url, true);
xmlhttp.send(JSON.stringify(data));

function successCallback(arr) {

}

Note: This code has not been tested yet.

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

Passing a function from a parent component to a child component in react.js

My current challenge involves invoking the function handleToggle() from the parent component in the child component. Despite everything looking good, when I execute this.clickAddGoal(stageContent);, it shows up as undefined class ParentClass extends Compo ...

Serializing JSON in Spring Boot with a parent table

Hello, I am in need of assistance with retrieving a JSON object from spring boot using an AJAX call. The JSON should contain daughter tables as well as the parent table. I previously encountered the issue of infinite recursion which I resolved using @Json ...

Issue: The data type 'void' cannot be assigned to the data type 'ReactNode'

I am encountering an issue while calling the function, this is just for practice so I have kept everything inside App.tsx. The structure of my class is as follows: enum Actor { None = '', } const initializeCard = () => { //some logic here ...

Analyzing the contents of a JSON file and matching them with POST details in order to retrieve

When comparing an HTTP Post body in node.js to a JSON file, I am looking for a match and want the details from the JSON file. I've experimented with different functions but I'm unsure if my JSON file is not formatted correctly for my needs or if ...

Refreshing a model using angular.js

I am attempting to reset values in the following way: $scope.initial = [ { data1: 10, data2: 20 } ]; $scope.datas= $scope.initial; $scope.reset = function(){ $scope.datas = $scope.initial; } However, this code ...

Meteor, enhanced with the dynamic Iron Router module and integrated

I am working on a project using Meteor (Meteor.com) and I want to incorporate iron-router for the page routing along with the pre-existing accounts-ui package for login functionality. Previously, my {{loginButtons}} functioned properly, but ever since I i ...

How can I use a JavaScript or jQuery function to choose a specific audio track that is currently playing locally?

Currently, I have developed a music app that features local mp3 files triggered by clicking on divs which are linked to the audio using an onClick function with the play() method. Additionally, there is a scrolling screen that displays the song's arti ...

SecurityError: The dubious operation triggers CORS to persist in its insecurities

I have developed an HTTP server using Express in Node.js. This server is currently running locally on port 3000. There is a served HTML page called "index.html" which makes AJAX GET requests for contents (in HTML format). These AJAX contents are also serv ...

Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have: <ul id="FirstLevel"> <li><a href="#">FirstLevel</a></li> <li>< ...

Javascript/Webpack/React: encountering issues with refs in a particular library

I've encountered a peculiar issue that I've narrowed down to the simplest possible scenario. To provide concrete evidence, I have put together a reproducible repository which you can access here: https://github.com/bmeg/webpack-react-test Here&a ...

Accessibility issues detected in Bootstrap toggle buttons

I've been experimenting with implementing the Bootstrap toggle button, but I'm having an issue where I can't 'tab' to them using the keyboard due to something in their js script. Interestingly, when I remove the js script, I'm ...

Is there an equivalent of numpy.random.choice in JavaScript?

The Numpy.random.choice function is a handy tool that allows you to select a sample of integers based on a specific probability distribution: >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0]) Is there a similar feature in Java ...

Mastering SVG Path Coordinates using Pure JavaScript

Is it possible to target and manipulate just one of the coordinate numbers within an SVG path's 'd' attribute using JavaScript? For example, how can I access the number 0 in "L25 0" to increment it for animating the path? function NavHalf ...

Can you explain the distinction between these codes?

function Example() { this.display1 = function() { alert(1) } } Example.prototype.display2 = function() { alert(2) } var e = new Example e.display1() e.display2() display1 and display2 both have the ability to trigger an alert showing a number. Do yo ...

Extracting information from a XHR using request

I am trying to extract the data from this specific website. However, the results I am retrieving are not matching the values displayed on the site. For example, when I run the code for a loan amount of 14000 and a duration of 48 months, the TAE value is ca ...

The functionality to save user likes in React is not properly functioning on the like button

I created a like button in React that saves my choices, but it seems to be not saving the choices of other users. Additionally, it doesn't appear to restrict only authenticated users from marking likes. Can someone please help me identify what I' ...

Optimizing Animation Effects: Tips for Improving jQuery and CSS Transitions Performance

Wouldn't it be cool to have a magic line that follows your mouse as you navigate through the header menu? Take a look at this example: It works seamlessly and smoothly. I tried implementing a similar jQuery script myself, but it's not as smoot ...

Enable checkboxes to be pre-selected upon page loading automatically

Although I've found a lot of code snippets for a "select all" option, what I really need is more direct. I want the WpForms checkboxes to be pre-checked by default when the page loads, instead of requiring users to press a button. My goal is to have a ...

What can be done to prevent unnecessary API calls during re-rendering in a React application?

On my homepage, I have implemented code like this: {selectedTab===0 && <XList allItemList={some_list/>} {selectedTab===1 && <YList allItemList={some_list2/>} Within XList, the structure is as follows: {props.allItemList.map(ite ...

A guide on how to associate data in ng-repeat with varying indices

Here is the data from my JSON file: var jsondata = [{"credit":"a","debit":[{"credit":"a","amount":1},{"credit":"a","amount":2}]}, {"credit":"b","debit":[{"credit":"b","amount":3},{"credit":"b","amount":4},{"credit":"b","amount":5}]}, {"credit":"c","debi ...