Guide to crafting an effective XHR request using AJAX

Here's a snippet of my basic web page:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body onload="start()">
  </body>
</html>

Below is the XMLHttpRequest function I've implemented:

function start(){
  //Defining the httpRequest variable
  var httpRequest;  

  //Creating an instance compatible with multiple browsers
  if (window.XMLHttpRequest) { // For Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
  } else if (window.ActiveXObject){ // For Internet Explorer 8 and older versions
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }  

  //Specifying what to do upon receiving response
  httpRequest.onreadystatechange = httpResult; 
  httpRequest.open("GET","http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", true);
  httpRequest.send();

  function httpResult(){
    if (httpRequest.readyState === 4 && httpRequest.status === 200){
      alert(httpResult.responseText);
    } else {
      alert("An issue occurred while making the request");
    }
  } 
}

Upon loading the web page, the function executes but triggers the "problem making request" alert thrice. No errors are showing up in the JavaScript console. Any insights on why the expected response isn't being received?

Answer №1

It appears that you may be breaking the rule of the same origin policy, a security measure in browsers that prohibits cross domain AJAX requests.

AJAX requests can only be made to the same domain as the script's origin. In this case, you are trying to make a request to http://data.mtgox.com, which is only allowed if your page is hosted on that exact domain – something that I assume is not true for your situation.

If the server supports CORS or JSONP, then it would be feasible to execute such a request.

Answer №2

Each time the property readyState changes, the onreadystatechange handler is triggered. This implies that your else statement will continue to execute until the readyState reaches 4.

The issue arises when you attempt to access the responseText property of httpResult, which actually refers to the onreadystatechange handler. It would be more appropriate to utilize httpRequest.responseText instead.

if (httpRequest.readyState === 4 && httpRequest.status === 200){
            alert(httpResult.responseText);
}

This particular problem is unrelated to CORS as your URL does permit CORS requests.

View a jsFiddle Demo here

Additionally, make sure to implement the onerror handler for detecting any potential XHR errors.

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

Is there a way to incorporate text at the end of a row in HTML?

I have a photo and some text on my website. The photo is displayed on the left side, while the text appears nicely on the right side. Now, I am looking to include an additional block of text below the existing text. How can I accomplish this? What steps ...

Sorting and Deduplicating MongoDB Data with Reduce

I'm currently using the Reduce function to generate a combined String of fields from an array. For instance, suppose I have an array of subdocuments named children - and each individual child contains a name field. For example: [ {name:"Zak"}, {n ...

Checking for the presence of text within a span tag - a simple guide

see fiddle if there is an already allotted time slot for the patient, change its color to yellow using jquery on the client side. In my example, if I assign a time slot for the first time, it turns green and when assigning another one, the previous slot tu ...

Determine the specific button that was clicked within a React component

I have a challenge with dynamically generated material UI buttons. I am trying to identify which button was clicked by obtaining the value of the name attribute that I assigned to each button. Is there a way to accomplish this? In essence, I need to retrie ...

Ensure that the function is executed only after the SVG has finished loading via Ajax

I've been searching for days, but haven't been able to find a solution: I have an external SVG file (800k) that needs to be fully loaded before the following function can be called. I received some help with loading the SVG, but I'm struggl ...

Spin an object around the global axis using the tween.js library

I'm trying to achieve a gradual rotation of a cube on the world axis using tween. Initially, I was able to rotate the cube around the world axis without tweening with the following code: rotateAroundWorldAxis(cube[1], new THREE.Vector3(0,1,0),degreeT ...

Is it advisable to encapsulate my entire Express server within a TypeScript class?

After working extensively with nodeJs, I have decided to explore developing applications in Typescript. Recently, I came across various blogs (like this one) that recommend wrapping modules and the app's entry point in a class when creating a RESTful ...

Is it possible for Angular.js to interact with JSTL expression language?

Is it possible for angular.js to interact with JSTL expression language? I am trying to generate ng-options using an array. Here is an example of what I am attempting to accomplish: <select ng-model="detail" ng-init="Categories = '${Categories}& ...

E2E testing on mobile devices with the Webdriver JavaScript client API from the official source

In the Appium documentation, it is noted that the wd.js Webdriver Javascript bindings are mentioned instead of the official bindings. While Appium can work with both clients, the wd.js offers specific mobile methods like touch and shake which are not prese ...

The code inside the if statement is somehow executing even when the if statement is not true

Similar Question: Issue with jQuery function running at inappropriate times I've spent several hours trying to figure out why my function isn't working properly. I have a function inside an if ($window.width() < 1000) statement, but it se ...

Understanding ReactJs component syntax: Exploring the nuances and distinctions

Currently diving into the world of Reactjs and working on creating a basic component. I'm puzzled about why this particular syntax for a component: import React, { Component } from 'react'; export default class AboutPage extends Component { ...

Modify the color of CSS for all elements except those contained within a specific parent using jQuery

I have a color picker that triggers the following jQuery script: //event.color.toHex() = hex color code $('#iframe-screen').contents().find('body a').css('color', event.color.toHex()); This script will change the color of al ...

Retrieve the radio button value from the HTML form

This website is designed to calculate ideal weight based on input data, but I am encountering an issue with the gender selection. The code seems to only recognize the first condition for female, while ignoring the else if condition for male. How can I fix ...

The jquery datepicker is malfunctioning after switching to another component

My current setup includes the following versions: jQuery: 3.3.1 jQuery UI: 1.12.1 AngularJS: 6 Here's a snippet of my code: <input id="test" type="text" class="form-control" value=""> In my component (component.t ...

Obtain the value of v-model in a child component within VueJS

In my Vuetify App, I have implemented a Vue2Editor using a custom component called text-editor. Here is how it looks: <vue-editor :value="text" @input="updateText" ></vue-editor> The props for this component are defined as follows: props ...

Problems with select tag change events

I encountered an issue with select tag onChange events. When I select a value from the select tag, it should display in a textbox that is declared in the script. It works perfectly when I remove the class "input" from the select tag, but I prefer not to re ...

Tips for structuring JSON data to retrieve numerous values

Creating a tool where users can enter their postcode to check for nearby windfarms is my current project. I have organized the data by named locations, and it's important to maintain that structure due to the specific API mapping tool I am using. Here ...

The process of extracting data using PHP's simpleXML

I am currently facing an issue with my code that only displays the first image instead of all the images in the XML file. I am using a foreach loop to traverse through the images node, but it seems to be returning just the first image. Any assistance on th ...

Node.js square brackets notation for functions [function] or [function: isBuffer]

Apologies for what may seem like a beginner question. I've been exploring the global variable in node.js and I'm puzzled by the syntax. It appears to be a JSON object, but it's formatted as follows: reallyExit: [Function: reallyExit], bindi ...

Compose an email without the need to access the website

Is there a way to send email reminders to users without having to load the website pages? In the reminder section, users can select a date for their reminder and an email will be automatically sent to them on that date without requiring them to access the ...