Is it possible to employ different formats other than XML when using XMLHttpRequest?

Is it possible to use a different format other than JSON or XML when making requests in JavaScript?

Can I request custom text or binary data instead?

Or are the options limited to just JSON and XML?

I'm curious to know...

a) How can I send a request without using XML or JSON?

b) Is there a way to receive the response as a plain string instead of an object?

Answer №1

A simple solution is to specify the content-type in the XMLHttpRequest header:

let req = new XMLHttpRequest();
req.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); // set your desired character set here.
req.open("GET", "yourtext.txt", true);
req.onreadystatechange = function() {
 if(this.readyState == 2) {
  alert(req.responseText);
 }
}
req.send();

Answer №2

Feel free to utilize various text-based formats such as XML, JSON, CSV, or simply text/plain.

I'm uncertain about the outcome when attempting to use a binary format.

Answer №3

Retrieving the outcome can be done in various ways:

  • You may receive a DOM document (in case of XML) by using the responseXML property, or
  • A string (irrespective of the format) by employing the responseText property

Certain browsers are even capable of returning it as an object if the data was in JSON format.

The option to obtain any content as a string gives you the flexibility to parse different formats on your own.

Answer №4

To ensure the content type is set to plain text, you can explicitly define it before using the send() method:

var httpRequest = new XMLHttpRequest();
httpRequest.open("POST", "/test.php");
httpRequest.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
httpRequest.send(content);

Answer №5

Aside from the previous mentions of the setRequestHeader function, it appears that according to the w3 specifications for the xmlhttprequest API, there are suggestions or constraints on the type of data passed in as headers (the first argument) but not for the actual values themselves (the second argument).

You can find the full specification here: http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method.

Based on my understanding, this means that any data type is acceptable for the requested transfer, but when it comes to the returned data, only text and xml formats are specified.

Of course, I could be mistaken in my interpretation.

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

XMLHttpRequest is unable to load due to the absence of an 'Access-Control-Allow-Origin' header on the requested resource

No matter how many different solutions I've attempted to implement from various sources, none seem to be working for me. Here's a snippet of code that I'm trying to execute within the setInterval method in the document.ready() function. f ...

The hierarchy of BabelJS classes and inheritance organization

I'm looking for a solution to configure Babel to load files in a specific order, ensuring that superclasses are loaded before child classes. Consider the following example with these files: src/fruit.js: export class Fruit{ constructor(color){ ...

What is the best approach for handling a situation where the data parsed from a JSON file is either null or yields no

I am facing an issue with displaying a toast message when the database table is null while parsing JSON data. Essentially, when there are no results or data found, I want to display a toast saying "Sorry no data found". Any assistance on this matter would ...

In an if conditional, the object keys are initially undefined, but I am able to access them within the if statement

I have an issue where I am comparing two JavaScript objects by stringifying them. The first object is easily accessible without calling the keys, so these comparisons work fine: if(JSON.stringify(response) == JSON.stringify(lastcmd)) if(JSON.stringify(res ...

What is the distinction between using localStorage and storing individual files when clicking?

Recently, I created a basic jQuery script that stores values such as "voted1", "voted2", and "voted3" in localStorage. However, I encountered an issue where all values are stored simultaneously on click, whereas I require them to be stored individually per ...

Using formidable to parse form data in Node.js

Hello everyone, I'm a beginner with node.js and I'm currently working on setting up a file/image upload script. After successfully installing node on my VPS, I came across this helpful guide that assisted me in setting up the app with formidable ...

Developing a real-time form that syncs with a MYSQL database for automatic updates

I am currently working on developing a form with multiple drop-down menus. The first dropdown is populated with 'Customer Name' data retrieved from my MYSQL database. Upon selection, the second dropdown menu below it should display the available ...

Differences in behavior between Javascript mousemove and jQuery mousemove in Firefox

I've developed a custom jQuery widget that allows users to draw on a canvas element and record their drawings. However, I encountered an issue in Firefox where the jQuery event wasn't working as expected. Surprisingly, the native JavaScript even ...

"Here's a cool trick: A guide on dynamically inserting a value into {% url tag %} using JavaScript within

Incorporating leaflet JS into a Django template, the aim is to display markers on a map where latitude and longitude are sourced from a queryset. Sending the queryset through views and utilizing the Django template language within <script> tags seeme ...

How can AngularJS effectively parse JSON data containing HTML elements?

We are experiencing difficulties in reading a json file containing html content. Here is the code snippet with the json data we are working with: Json data: { "aboutContent": { "listItems": [{ "title": "Investors", "de ...

Confirmation message using ajax/jquery when submitting a form

Feeling exhausted, yet unable to accomplish what I desire. I would appreciate a confirmation message like "Thanks for submitting this form" to appear after the user clicks on the submit button (and then sent to my email). The website consists of only one ...

Encountering an issue with Angular directive attributes

I am attempting to create an angular directive that will extract a substring from a passed-in attribute. Below is the code I have written: HTML: <body ng-controller="MainCtrl"> <div><substring message="This is a test."></substri ...

Issue with error handling not being triggered when calling SAPUI5 function()

IBAN validation within a SAPUI5 Wizard is causing some issues for me. I am utilizing a functionImport on a V2 ODataModel (sap.ui.model.odata.v2.ODataModel) to perform this validation. Despite receiving a 202 status code, the request actually failed. Here ...

Utilize a display value while maintaining the v-model binding in Vue.js

Can't seem to figure this one out. I'm using Quasar Framework, but it seems like more of a Vue issue. I have a multiple-select UI component with a list of objects as options that I want to display. The v-model will bind to the currently selected ...

Passing a PHP variable between PHP files with the help of jQuery

I'm facing a minor issue. I'm trying to pass a PHP variable from one PHP file to another using setInterval. However, I'm unsure of how to include the PHP variable in my jQuery code. Here is the content of first.php: <?php $phpvariable= ...

How can I prevent users from selecting a date earlier than the start month in angular's date picker or make it

I am looking to implement a feature where the user cannot select or edit the start date for the first two months after the initial start date. If any month is selected other than those two, then I want to calculate the date with an additional 2 months adde ...

Dynamically select checkbox groups based on items already listed in a textarea

Hello! Would you be able to review this example and provide guidance on how I can use jQuery to dynamically select the checkboxes that have the same text as in the textarea below? <br /> <br /> Default Items From Database <br /> < ...

JavaScript FormData class does not recognize disabled and checked states on Bootstrap 5 switches

I am implementing a Bootstrap 5 switch input that I need to be mandatory, meaning it should be checked by default and not uncheckable. The official documentation suggests combining the attributes checked and disabled. However, it seems like the Javascrip ...

Exploring the ‘ref’ feature in React alongside Material-UI

In my attempt to access input data through React's "ref" attribute on a TextField in Material-UI, I've encountered some difficulties. It doesn't seem straightforward to achieve this using the 'inputRef' or 'inputProps' me ...

When using JsonConvert.DeserializeObject from Newtonsoft.Json, the issue of losing a non-printable ASCII character (specifically the group separator) during deserialization may

I have encountered a puzzling issue that I am struggling to resolve. My current task involves deserializing JSON data using Newtonsoft.Json. After inspecting the raw JSON string, I noticed certain character sequences: { '\\', 'u&ap ...