What is the best way to transmit data using a 'GET' request with XMLHttpRequest in JavaScript?

Thank you for taking the time to read this post.

I'm looking to send data in a GET request using XMLHttpRequest.

function useAjax(url,data){
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function(e) {
            const resData = JSON.parse(xhttp.responseText) ;
            setResponseData(true,resData)
        }
        xhttp.open("GET", url, false);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(data);
   }

I attempted to modify the parameters in the open function like xhttp.open("GET", url, [false,data]);

However, I still did not see any results.

Answer №2

When working with a C# based API, you have the option to utilize [FromHeader] in your method signature and then pass the object in the header using XMLHttpRequest.setRequestHeader...

const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://your-host/route/endpoint');
...
xhr.setRequestHeader('MyFilter', {"item":"value", "item":"value" })
xhr.send();

Next, in your controller (C#):

[HttpGet("route/endpoint")]
public async Task<IActionResult> GetListOfMyObject([FromHeader] MyFilter filter)
{
    var result = QueryForDataUsingObject(filter);
    ...
}

The object will be automatically deserialized into the necessary type.

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

What are the methods to alter validation for a Formfield based on the input from other Formfields?

My aim is to create a Form where input fields are required only if one or more of them are filled out. If none of the fields have been filled, then no field should be mandatory. I came across a suggestion on a website that recommended using "valueChanges" ...

If you refer to a function, are you personally calling the function or asking the reference to call it?

From what I understand, and please correct me if I'm mistaken, when a variable is assigned to a function in the form of a function expression, it doesn't hold the function in the same way that it holds a primitive value. The variable simply refer ...

Acquire Laravel notification data through the power of AJAX

I successfully implemented a notification feature in Laravel, and it was working perfectly. However, I encountered an issue when trying to display the notification details in a dynamic modal upon clicking on the notification. I couldn't find a way to ...

Is it possible to combine ng-class with conditional expression and ng-class with string syntax in a single statement?

To assign classes based on the ngRepeat index, I am using ng-init="myIndex = $index". With this setup, I can apply classes like color-0, color-1, color-2, etc. by using ng-class='"color-" + myindex'. Furthermore, I need to add a different class ...

The error message "AmCharts: Uncaught TypeError: Unable to retrieve the property 'mouseX' as it is undefined" appeared

When utilizing AmCharts for stock-related events, I encountered an unusual error in my console window: Uncaught TypeError: Cannot read property 'mouseX' of undefined at b.followCursor (amcharts.js:271) at b.showBalloonReal (amcharts.js:1 ...

Utilizing the HTML method of jQuery on a jQuery element

Currently, I am attempting to modify the inner html of an element. When I utilize the following code: $('.best-photos-button')[0].innerHTML="Add More Photos"; the change is successful. However, if I try to use .html() instead of ".innerHTML" in ...

Playing with JSON data in React

I am currently working on developing my React UI to be dependent on a JSON file. Despite reading numerous articles, I have yet to find a solution that is both understandable and applicable to my project. The closest resource I found is about loading json d ...

Angular - Switching Displayed Information

I am currently working with Angular 4 and I am attempting to switch between contenteditable="true" and contenteditable="false" Here is what I have so far: <h1 (dblclick)="edit($event)" contentEditable="true">Double-click Here to edit</h1> Al ...

Can you explain how I can use AJAX in HTML to change the text of a link once it has been clicked on?

I have a link titled Save to Favorites. This link triggers an AJAX function when clicked, which updates the text of the link to say Remove from Favorites. Clicking it again changes it back to Save to Favorites. What code should I include in the link itsel ...

the width of the table body is narrower than the table itself

I'm working on a table that has a fixed first column and needs to be vertically scrollable. I'm almost there with my CSS code, but the table rows are not as wide as the columns and I'm unsure why this is happening. .table th:first-child, ...

React Redux Connect MapState not refreshing when filtering an item from a list

It seems like I may have misunderstood something or made a mistake when trying to subscribe to changes on a specific item within a collection in my store. My component isn't receiving updates unless I directly subscribe to the list. The following cod ...

Leveraging spread syntax and styling for array string interpolation in JavaScript

Imagine I have an array such as [1,2,3] and my goal is to insert its values into a string format like: the values are (?, ?, ?) Can anyone suggest a simple solution for this? I am aware of the spread operator ...[1,2,3], and it's feasible to conver ...

Differences between utilizing computed variables versus useState and useEffect

Is there any downside to initializing a computed variable instead of using useState/useEffect to track it when its value can be fully derived from another property? Let's consider the following example: /** * ex paymentAmounts: [100, 300, 400] */ co ...

Creating a "return" button for an editing form in AngularJS Datatables with the help of a form directive

Using AngularJS Datatables, I implemented a grid with additional "edit" and "delete" buttons in the last column. How is the grid/table rendered? HTML <!-- Required CSS and JS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/li ...

My desire is for every circle to shift consecutively at various intervals using Javascript

I'm looking to draw circles in a sequential manner. I am trying to create an aimbooster game similar to . Instead of drawing all the circles at once, I want each circle to appear after a few seconds. The circles I've created currently do not g ...

Transforming an ASP.NET webpage into a PDF format using Ajax Tab Container

I'm currently working on a website that involves a lot of data import and export. The user's data is being displayed in an ajax tab container, but I've run into an issue when trying to export this data to PDF: Script control 'TabPanel1 ...

Retrieving metadata using breeze is taking too long

Using breeze in my MVC 4 application to fetch data from a remote SQL Server database with about 40 entities. Surprisingly, the loading of metadata is taking longer than expected, ranging between 14s and 35s even though the size is just around 600kb. Howev ...

Trying to update React and Electron, encountering the error message "global is not defined"

I have an Electron + React app that has not been updated in a couple of years, initially utilizing the following packages: "@rescripts/cli": "^0.0.13", "@rescripts/rescript-env": "^0.0.11", "electron": &quo ...

Select the picture to update the content of the text box

Seeking advice and guidance on a project. I have a variety of color icons and I want to set it up so that when someone clicks on a color icon, the name of the color is inserted into a hidden text field. The code for my hidden text field is as follows: &l ...

Trouble with Basic JavaScript Comparison Function

I'm facing an issue with a JavaScript comparison that doesn't seem to be working. It's puzzling why it's skipping to line 12302 and setting showNoDataText = true. The logic dictates that it should be false since the array length of 285 ...