JavaScript - Asynchronous JavaScript and XML

function sendRequest(settings) {
 settings = {
  type: settings.type || "POST",
  url: settings.url || "",
  timeout: settings.timeout || 5000,
  onComplete: settings.onComplete || function(){},
  onError: settings.onError || function(){},
  onSuccess: settings.onSuccess || function(){},
  data: settings.data || ""
 };
 if (typeof XMLHttpRequest == "undefined") {
  XMLHttpRequest = function(){
   try { return new XMLHttpRequest(); } catch(e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   return null;
  };
 }
 var xhr = new XMLHttpRequest();
 xhr.open(settings.type, settings.url, true);
 var timeoutVal = settings.timeout;
 var requestFinished = false;
 setTimeout(function(){
  requestFinished = true;
 }, timeoutVal);
 xhr.onreadystatechange = function(){
  if (xhr.readyState == 4 && !requestFinished) {
   if (httpSuccess(xhr)) {
    settings.onSuccess(httpData(xhr, settings.type));
   } else {
    settings.onError();
   }
   settings.onComplete();
   xhr = null;
  }
 };
 xhr.send();
 function httpSuccess(response) {
  try {
   return (response.status >= 200 && response.status < 300) || response.status == 304 || navigator.userAgent.indexOf("Safari") >= 0 && typeof response.status == "undefined";
  } catch(e) {
   return false;
  }
 }
 function httpData(response, responseType) {
  var contentType = response.getResponseHeader("content-type");
  var data = !responseType && contentType && contentType.indexOf("xml") >= 0;
  data = responseType == "xml" || data ? response.responseXML : response.responseText;
  if (responseType == "script") eval.call(window, data);
  return data;
 }
}
function encode(data) {
 var serializedData = [];
 if (data.constructor == Array) {
  for (var i = 0; i < data.length; i++) serializedData.push(data[i].name + "=" + encodeURIComponent(data[i].value));
 } else {
  for (var key in data) serializedData.push(key + "=" + encodeURIComponent(data[key]));
 }
 return serializedData.join("&");
}

The issue with this code needs to be identified. What do you think is causing the problem?

Answer №1

It seems unlikely that you'll find the perfect solution to this question, as most developers rely on Javascript libraries to tackle it!

Why not follow suit and go the quicker route?

If you're unfamiliar with it, consider checking out JQuery: http://api.jquery.com/jQuery.ajax/

Answer №2

update httpData(r.type) { with update httpData(r,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

The button works properly in JSFiddle, however, it is not able to clear the ordered list in the

DEMO Creating a script that captures mouse click coordinates and appends them to a list. The functionality works, except for an issue with the clear button not working properly. After making corrections in jsfiddle, the script functions correctly. Howeve ...

Development versions of npm libraries

Lately, I came across a library called react-3d-components that offers some d3 react components with basic charts. It's an impressive collection of components. However, when trying to access the source code due to incomplete documentation, I found my ...

What is the best way to iterate over my JSON data using JavaScript in order to dynamically generate cards on my HTML page?

var data = [ { "name":"john", "description":"im 22", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d7e7f0c2b212d2520622f">[email protected]</a>" }, { "name":"jessie", ...

Invoking a JavaScript function within a different JavaScript function

Is there a way to ensure that the JavaScript function works properly even when using a text editor? var editor = $('#CKEditor1').ckeditorGet(); editor.on("instanceReady", function () { this.document.on("keydown", function (event) { ...

Current recommended method for updating innerHTML with properly formatted text?

My understanding is that using innerHTML on an element can be risky, as malicious users could potentially inject harmful content such as <script> tags. This question shows there are multiple alternative tags, some of which are non-standard. In my s ...

The Fancybox iFrame is not appearing on the screen

I am facing an issue with the html and javascript code I have. The html looks like this: <ul> <a class="iframe" href="/posting/form?id=8"><li>Publish</li></a> </ul> and I am using the following javascript: <scr ...

Instructions on invoking a function from one controller within another controller

Is it possible to invoke a function from one controller in another controller? I attempted the following but encountered failure: <div ng-app="MyApp"> <div ng-controller="Ctrl1"> <button ng-click="func1()">func1</button> ...

JavaScript: Determine the wild decimal value produced by subtracting two decimal numbers

In the process of creating a service price tracking bot, I encountered an issue with displaying price decreases. Here is an example of what it currently looks like: Service price decreased from 0.10 to 0.05 If you buy right now, you could save <x> ...

The MUI multiple select feature is experiencing issues following the addition of a new button

I'm having trouble adding buttons below a select dropdown menu with a specific height. When I try to put the menu item inside a div, the multiple select stops working and I have no idea why. Can someone help me figure this out? Check out my CodeSandb ...

Ways to retrieve all elements based on their class names?

What is the equivalent of using $('.class') in JQuery to get all elements by class name with pure JavaScript? ...

What is the reason behind AngularJS throwing an error related to bad augmentation?

Whenever I try to update the src link in my Angular code from version 1.2.2 to 1.5.0, I encounter an error. The code works perfectly fine with 1.2.2, but switching to 1.5.0 throws an error. I want to upgrade it to 1.5.0, so what changes do I need to make ...

Are foreign characters the culprit behind the JSON parsing problem?

I am encountering an issue while attempting to parse a field containing JSON data returned from an API. The data includes various unusual characters like East Asian symbols and curly quotes, causing this error to appear. I am unsure of how to resolve it - ...

Setting up a custom global variable in nuxt.js using vuetify

As I work on developing my app with Nuxt, I find myself frustrated by the need to constantly write an if statement in my pages using this.$Vuetify.breakpoint.name == 'xs' for handling responsiveness. Instead, I want to create my own variable for ...

Tips for implementing custom fonts in NextJS without relying on external services

Utilizing Fonts in NextJS I have been researching various methods for using self-hosted fonts with NextJS. When attempting the following code, I encountered a [ wait ] compiling ...: @font-face { font-family: 'montserrat'; src: url(&a ...

Create a dynamic animation using Angular to smoothly move a div element across the

I currently have a div with the following content: <div ng-style="{'left': PageMap.ColumnWrap.OverviewPanelLeft + 'px'}"></div> Whenever I press the right key, an event is triggered to change the PageMap.ColumnWrap.Overvie ...

Setting up a functionality for a PHP-generated select option

When the main select tag "category" is changed, it triggers a PHP script to display a new select tag: <select id="category" onchange="showme(this);"> <option value="txt">text</option> <option value="img">image</ ...

Ways to update a specific div upon clicking an image

Is there a way to refresh a div using an image click? I have an image with the id 'sellhide' and another div with the id 'sellChart'. Below is the code: <div class="col-xs-12 col-lg-6 col-sm-6 col-md-6 index_table_three" id="sellCha ...

Guide on transmitting data from a child component to a parent object in Vue.js?

When I attempt to utilize a child component with custom form inputs and emit those values to the parent component, I encounter an issue where one input value disappears when another input value is entered. Let me showcase some code: Child Component <tem ...

Slicknav is failing to appear on the screen, although it is being

After spending hours trying to implement a slicknav menu into my school project, I'm stuck and seeking guidance. Despite having some coding experience, I can't seem to find the solution to my problem. Any help, insight, or tips on fixing or impro ...

The cookie set in express.js is not being successfully set in React.js, even after setting up CORS and using credentials: 'include'

I have been struggling to set a cookie from my express backend using a React frontend. The cookie shows up in the response header, but for some reason, the browser refuses to set it. I've tested this on Chromium and Firefox, with no success. Interesti ...