Error occurs when making an Ajax request to a web URL using JavaScript

Lately, we have been successfully utilizing Ajax calls within our applications for URLs that are part of the server domain. However, when attempting to make an Ajax call to a URL on the web, it consistently fails without providing a clear error message. Despite conducting thorough research online with the information available, I've yet to uncover a reasonable cause or solution to this perplexing issue.

Here is a simplified version of the Ajax call code snippet:

var url = "http://www.google.com";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    alert('done');
    }
  };
xmlhttp.open("GET",url,true);
xmlhttp.send();

The problem arises specifically when the URL is from an outside domain like Google, resulting in various failures across different browsers.

In IE9, 'Javascript error: Access denied' occurs along with 'could not complete the operation due to error c00c023f' as the status.

On Chrome and FF, although no log errors are displayed, the status remains at 0.

Unfortunately, regardless of the browser, the Ajax call always ends in failure.

What could be causing this peculiar issue? It seems unlikely to be a network problem since accessing the Google URL directly via the browser works just fine. What might be preventing the Ajax call from functioning properly within the browser?

Best Regards, Vijay.K

Answer â„–1

Unfortunately, Cross Domain Queries do not function properly in IE 9, Chrome, and Firefox due to security concerns. Despite this limitation, many developers still resort to using XHR. However, why not take advantage of jQuery's powerful $.ajax method instead? You can easily implement it like so:

$(document).ready(function(){
    $.ajax({
        url: "https://www.example.com/",
        success: function(){
           alert("Request successful!");
        }
    });
});

The main issue arises when attempting to access a cross domain resource, resulting in a security breach where the status code will invariably be 0. Feel free to examine the provided fiddle for further clarification.

Fiddle: http://jsfiddle.net/abc123/

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 feature was implemented to make the delete button visible on the row only when the user hovers over it

How can I make the delete button only appear on the row that the user hovers over using Bootstrap? I have already achieved it using CSS, but I am looking for a way to implement this functionality with Bootstrap. Here is a snippet of the code. <!DOCTYP ...

Discovering the presence of line breaks

I have searched extensively on Google, but I am struggling to find a definitive answer. My goal is to create an email simulation where users can input text into a textarea and save it to the database. They should then be able to return to the page later a ...

Converting a JavaScript map into an array with ES6: A step-by-step guide

I am in need of a solution to convert a JavaScript map into an array with a specific format: [ { name: "21 years old", totalUsers: 2, }, ... ] For example, if I have the following map: const ages = { "21": 2, "18 ...

A guide to dynamically retrieving data from a MySQL database and populating HTML select options using JSP and AJAX for a pair of select option boxes

I am currently encountering an issue with fetching data from a MySQL database and populating it into an HTML select option using AJAX. The problem is that the second select box is displaying the content of both the first text box and the result of the seco ...

Extracting object properties and tallying their occurrences

How can I extract a single property from an array of objects like the following: [{"name":"Bryan","id":016, "counter":0}, {"name":"John","id":04, "counter":2}, {"name":"Alicia","id":07, "counter":6}, {"name":"Jenny","id":015, "counter":9}, {"name":"Bryan" ...

Why is it that the form consistently comes back as invalid?

I populated my edit form inputs with data from an API response, https://i.sstatic.net/2HUpr.png When I click on Continue, the validate() function is triggered. validate() { this.$refs.form.validate() console.log('this.$refs.form.va ...

Using JSTL tags may result in returning null or empty values when making Javascript calls or populating HTML

This strange error is puzzling because it appears on some of the webpages I create, but not on others, even though the elements are exactly the same. For instance, this issue does not occur: <main:uiInputBox onDarkBG="${hasDarkBG}" name="quest ...

Sending a PHP error back in response to an Ajax call

My PHP script needs to be called with AJAX, but I keep getting an error message that says "Error:email=my_email&password=myPassword". Check out the PHP script below: <?php session_start(); require "db_config.php"; if ($_SERVER["request_method"] ...

Is there a way to access the filtered or organized rows in the Quasar Q-Table?

I have encountered a roadblock in my project. Despite installing Quasar version 2.0.0, I realized that it lacks a property to access the filtered or sorted rows. Previous versions of q-table had a computedRows property which was missing in the latest ver ...

JavaScript: handle null values along nested object keys by providing a default value

I am dealing with a complex JSON structure that requires pulling out specific information like this let result = data["a"]["b"][0]["c"]["d"][0]["e"][0] What is a streamlined approach to extract the data? A ...

Update the color of a form input using jQuery when the value has been modified

I need to modify the font color of a jQuery UI Select when the value is edited. The structure of the DOM is like this: <dd> <select class="filter large" name="xx" style="display: none;"> <option value="0">--</option> ...

Guide to configuring a robust schema and validation with joi

Currently in the process of setting up validation using the joi package, encountering syntax-related issues along the way. The schema in place is simple, checking for a valid number and verifying if the ID exists in the database. export default router.pos ...

The function iframe.scrollTo() is not effective for scrolling through Excel or PowerPoint documents on an iPad

I am trying to create a custom scrolling feature for iframe content specifically for iPad. Currently, I have set up my iframe like this: <div id="scroller" style="height: 300px; width: 100%; overflow: auto;"> <iframe height="100%" id="iframe" ...

Notification from the rear side

A WebMethod has been implemented to receive a value in the 'lvl' string from the front-end. This string is then checked using the 'getDuplicate' procedure to determine if the value already exists in the database. If the value is present ...

Is it necessary to call cancelAnimationFrame before the next requestAnimationFrame?

Within my React timer application, I am unsure if I need to always call cancelAnimationFrame before the next requestAnimationFrame in the animate method. I have come across conflicting information - one source mentioned that if multiple requestAnimationFr ...

Is there a Ruby gem similar to Readability that anyone can recommend?

Readability is a nifty JavaScript tool that magically transforms a cluttered HTML page into a more user-friendly format. I'm on the hunt for a Ruby implementation or something along those lines - does anyone know of a library that offers similar funct ...

the deactivation of my rollover class is being caused by my float class

With the assistance of a generous contributor on stackoverflow, I was able to overlay different colored CSS boxes onto various images. These boxes could be removed upon mouseover, revealing the images beneath. You can view the code I used on fiddle here. ...

Struggles with ajax and JavaScript arise when attempting to tally up grades

Currently, I am facing an issue with my JavaScript. The problem arises when trying to calculate marks for each correctly chosen answer based on information from the database. If an incorrect answer is selected, the marks are set to '0', otherwise ...

"Creating a new object in ThreeJs by deriving from an existing object

After importing an .obj file, I successfully created an object that I now want to clone and assign unique coordinates to. Specifically, I have a wall to which I have attached another object (a window) as a child. Everything functions correctly when movin ...

The ambiguity surrounding the timing of decorator invocation in TypeScript

My understanding was that decorators in TypeScript are invoked after the constructor of a class. However, I recently learned otherwise. For example, the primary response on this thread suggests that Decorators are called when the class is declared—not wh ...