Can AJAX function properly when the server-side code is hosted on a separate domain?

After opening Firefox's scratchpad and inputting the following code...

function ajaxRequest()
{
var xmlhttp;
var domainName = location.host;
var url = 'http://leke.dyndns.org/cgi/dn2ipa/resolve-dns.py?domainName=';
url = url + domainName + '&x=' + Math.random(); // x= to avoid browser caching;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    alert(domainName+'='+xmlhttp.responseText);
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

ajaxRequest();

I am curious as to why my ajax code functions only within the same domain as the remote script (http://leke.dyndns.org), but fails in other domains like .

If it helps, here is the cgi script side...

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os, cgi, cgitb, socket
cgitb.enable()

cgiData = cgi.FieldStorage() # Domain Name
domainName = cgiData.getvalue('domainName')
ipa = socket.gethostbyaddr(domainName)
sendIpa = ipa[2][0]

print 'Content-Type: text/html;charset=utf-8'
print ""
print sendIpa

Answer №1

Unfortunately, no, it will not work. This is intentional and serves as a security measure known as the same origin policy to prevent any potential cross site scripting attacks.

There is a workaround called JSONP if absolutely necessary, but it's advised against due to the risk of allowing another website (which could potentially be compromised by malicious actors even if trusted) to manipulate the logged in user's data without permission.

Answer №2

It may seem impossible in conventional methods, but there is a way to execute it by running server-side code on a separate domain.

To accomplish this, you need to implement the following changes on the server side:

Within the server settings, configure Access-Control-Allow-Origin as a Response Header.

Access-Control-Allow-Origin : * //allow access for all other domains

or 

Access-Control-Allow-Origin : <your_domain_name> // restrict access to only your domain

Reference: https://developer.mozilla.org/en/http_access_control

[Example]

You can successfully perform an ajax call to the http://xyz.com?x=a URL from a different domain, provided that the response header of the http://xyz.com?x=a URL includes the Access-Control-Allow-Origin field with your domain name or '*'.

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

Having difficulty accessing a PHP ajax post request

I've scoured every resource but can't seem to find a solution to this issue. I'm in the process of writing an ajax script, however, I am struggling to retrieve the correct value from the POST request. Here is the code I have so far: <t ...

The issue with the material design checkbox change functionality not functioning as expected

Currently, I am attempting to dynamically set the state of checkboxes to either true or false. The following code snippet demonstrates what I have tried so far: for(var i = 0; i < bookmakers.length; i++) { $('#' + bookmakers[i].id + &apos ...

Tips for retrieving the ID of a dynamic page

In my Higher Order Component (HOC), I have set up a function that redirects the user to the login page if there is no token. My goal is to store the URL that the user intended to visit before being redirected and then push them back to that page. However, ...

Using API JSON, fill the second dropdown list based on the selection made in the first dropdown

I need help in populating data in the 2nd drop-down list based on the selection made in the 1st drop-down list. I am currently using AJAX to fetch and display the data in the 2nd drop-down list. Below is the JSON output when facID = F09: Here is the AJAX ...

How to create a calendar selection input using PHP?

Before I start writing the code myself, I am searching to see if there is already a solution available or if someone has previously outsourced the code. Below is an example of my date selection: I want to create a feature where selecting a month will aut ...

When comparing `xhr.onload = () => {resolve();}` and `xhr.onload = resolve();`, it is important to note the distinction in syntax

function bar(){ return new Promise((resolve,reject)=>{ const xhr = new XMLHttpRequest(); xhr.open(method,url); xhr.onload = ()=>{ resolve(xhr); }; xhr.send(); }) } The code snippet shown above performs as expected Howe ...

Error with WooCommerce checkout causing input values to disappear upon clicking or submitting

I am facing an issue where I need to set #billing-postcode to a specific value using a JS script. When I input jQuery('#billing-postcode').val('2222') on the checkout page, the input displays the value 2222 with the Postcode label abov ...

Arranging Text and Images in HTML/CSS to Ensure Optimal Placement When the Window Size Changes

Hello fellow coders! I've recently started diving into the world of website development and I have a query regarding positioning elements and handling window resizing. Can anyone help me out? I'm trying to center an image, a message, and a passw ...

Is it possible to install in a directory other than the one specified in package.json

I have organized my folders exactly how I want them to be. In one specific folder, all of my configuration files reside (most importantly package.json). I am looking to install this package.json configuration in a different path, specifically c\instal ...

Implementing a switch to trigger a JavaScript function that relies on a JSON object retrieved from a GET request

Having some trouble using a toggle to convert my incoming Kelvin temperature to Celsius and then to Fahrenheit. It loads properly as default Celsius when the page first loads, but once I try toggling the function outside of locationLook, it doesn't se ...

Trouble with using $.ajax to call a PHP function

Hey everyone, I hate to ask for help but I'm really stuck on this issue. I've tried everything and followed all the scenarios on this site, but I just can't seem to get it working. I even added alerts and echoes, but the function doesn' ...

How to Use Ajax with Laravel Blade Templates

Recently, I've been diving into the world of implementing Ajax in Laravel Blades. Despite my efforts to find tutorials, everything seems quite confusing to me. I appreciate your patience as I navigate through this. One specific area that I'm loo ...

Every time I attempt to submit the login form on the Ionic and Angular page, instead of capturing the values of the form group, the page simply refreshes

Struggling with submitting the login form in Ionic and Angular? When attempting to submit, the page reloads instead of capturing the form group values. I am utilizing angular reactive forms and form builder within the ionic framework. Need assistance in id ...

Utilize the useRef hook in React to enable copying text to the clipboard

Looking to implement a copy to clipboard functionality in React using the useRef hook? Want to accomplish this without relying on any additional libraries? Take a look at my code snippet below. Currently, I'm encountering an error stating myRef.curren ...

Assigning a class to a header upon loading the page from various sections at random

After scrolling, I used JavaScript to add a class to <header>. Here is the code snippet: $(window).scroll(function(){ var top = $(window).scrollTop(); if(top>=1){ $("header").addClass('bg-header'); } else ...

A guide on updating URLs that are not enclosed within an anchor tag using JavaScript

In my current scenario, I am dealing with text that includes URL links presented in two different formats. www.stackoverflow.com <a href="http://www.stackoverflow.com">Stack over flow</a> My objective is to create a straightforward function ...

Ways to retrieve information from JSON

I am currently trying to access the values of an object that is within an array which is inside another object. The data is structured as follows: [{ "id": "99a4e6ef-68b0-4cdc-8f2f-d0337290a9be", "stock_name": "J ...

What causes JavaScript to be unable to run functions inside other functions?

Functional languages allow functions to be executed within the argument brackets of nested functions. In JavaScript, which drew inspiration from Scheme, what is the equivalent? f( f ( f ( f))) console.log( 1 + 1 ) //2 How does JavaScript execut ...

Angucomplete-alt fails to display dropdown menu

On my website, there is a textarea where users need to input the name of a group project. The goal is to implement autocomplete functionality, so as users type in the project name, a dropdown menu will appear with suggestions of existing projects to assist ...

NativeScript encountered an error while trying to locate the module 'ui/sidedrawer' for the specified element 'Sidedrawer'

Currently, I am in the process of developing a simple side-drawer menu for my NativeScript application by following this helpful tutorial. I have successfully implemented it on a single page using the given code below. starting_point.xml: <Page xmlns ...