Confused by CORS and XMLHttpRequest()

I’m trying to set up my page to pull data from an external table which I control. At this point, there are no errors, yet I’m not pulling any data (just 4 records of 4 columns) from the server. I’m using an ajax script from http://www.w3schools.com/php/php_ajax_database.asp and CORS (cross-origin resource sharing) script from http://www.html5rocks.com/en/tutorials/cors/ to read the data. However, I’m still not proficient enough in JS to figure out how the pieces go together. Anyone want to take a gander and see what may be failing in the HTML page I have?

<body>

	<form>
		<select name="users" onchange="showUser(this.value)">
		<option value="">Select power type</option>
		<option value="1">Electric</option>
		<option value="2">Nitro</option>
		</select>
	</form>
	<br>
	<div id="txtHint"><p>(Data will be displayed here)</p></div>

<script>

/* ****************** CORS begin ***************** */
var url = 'http://www.myDomain.com';
var xhr = createCORSRequest('GET', url);
	
// Create the XHR object
function createCORSRequest(method, url) {
	var xhr = new XMLHttpRequest();
	if ("withCredentials" in xhr) {
		xhr.open('GET', url, true);
	} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE
		xhr = new XDomainRequest();
		xhr.open('GET', url);
	} else {
// CORS not supported
		xhr = null;
		document.getElementById("txtHint").innerHTML = "CORS not supported.";
	}
  return xhr;
}

// Make the actual CORS request.
function makeCorsRequest() {

  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  // Response handlers.
  xhr.onload = function() {
    var str = xhr.responseText;
  };

  xhr.onerror = function() {
    document.getElementById("txtHint").innerHTML = "A cryptic error message.";
  };

	xhr.send();
	showUser(str);
}

/* ****************** CORS end ***************** */

function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML = "";
  return;
  }
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)
    {
    document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
    }
  }

// Pass the select option to PHP page

xmlhttp.open("GET","http://www.myDomain.com/getcars.php?q="+str,true);
xmlhttp.send();
}
		</script>
	</body>

I’m not even sure which should execute first, CORS or XMLHttpRequest.

If I put a console.log here …

xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			console.log(responseText);
			document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
		}

… the console output is “responseText not defined.” How do I define this? This may be why there are no results. Tools console is also outputting:

XHR finished loading: GET “http://www.MYDOMAIN.com/getcars.php?q=electric”.

… but there is not output on the HTML page.

Are you sure the domain you request data from accepts CORS requests? If not, you’d have to fix that first :slight_smile:

My .htaccess file has:

Header set Access-Control-Allow-Origin “*”

Is that enough?

This is my code as it presently stands:

<body> 
<input type="button" class="buttonClass" onclick='window.location="index.html"' value="Return">
<div class="segment">
<h2>Serving Data from External Server</h2>
	<form action="" method="GET">
		<select name="users" onchange="showUser(this.value)">
		<option value="">Select power type</option>
		<option value="electric">Electric</option>
		<option value="nitro">Nitro</option>
		</select>
	</form>
	<br>
	<div id="txtHint">(Data will be displayed here)</div>
</div>

<script>

var request = new XMLHttpRequest();
var url = 'http://www.MYDOMAIN.com/';

// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

function makeCorsRequest() {
  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }
  xhr.onload = function() {
    showUser(str);
    console.log("onload");
  };
  xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
  };

  xhr.send();
}

function showUser(str)
{
	if (str=="") {
		document.getElementById("txtHint").innerHTML = "Please make a selection.";
		return;
	} 
	document.getElementById("txtHint").innerHTML = "Getting data ...";
// for IE7+, Firefox, Chrome, Opera, Safari
	if (window.XMLHttpRequest) { 
		var xmlhttp=new XMLHttpRequest();
	}
// for IE6, IE5 - not used on Android
	else { 
		var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			var txt = xmlhttp.responseText;
			console.log("responseText = " . txt);  // "undefined"
			document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
		}
	}

// Need full URL to page, since this HTML page is not on server.
	xmlhttp.open("GET","http://www.MYDOMAIN.com/getcars.php?q="+str,true);
	xmlhttp.send();
}



		</script>
	</body>

The “txtHint” field remains empty after the process.

Console output:

XHR finished loading: GET “http://www.MYDOMAIN.com/getcars.php?q=electric”. ajaxDB.html:156

undefined

At last, this is working! Solved.