John Smith John Smith - 1 year ago 50
Javascript Question

Why does this code not function correctly?

I'm currently trying to learn Ajax and have been following a tutorial. I have created the following script:

<!DOCTYPE html>


<script type="text/javascript">
function MyFunction(){

var xmlhttp;

xmlhttp = new XMLHttpRequest();

else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){

document.getElementById("MyDiv").innerHTML = xmlhttp.responseText;
}"POST", "command.php", true);




<button onclick="MyFunction()">Execute</button>

<div id="MyDiv"></div>



I then have a php file named command.php which just echos the word "success".

Obviously the intended purpose of this script is to return the word "success" when the execute button is clicked. I have followed the tutorial for this very precisely, so I'm unsure of what's wrong with what I've written.

I've also looked at other Ajax tutorials, to see what they might have done differently. It seems that some variants of Ajax look very different to others. I mean by this, a lot of tutorials involve code looking like what I've written, but many others (such as this one) look rather different and involve many '$' signs. Why is this?

Answer Source

Looks like maybe a copy/paste error. I'm guessing:

   if(ajaxRequest.readyState == 4){

should be:

   if(xmlhttp.readyState == 4){

Also, it doesn't sound like you're using your browsers dev tools. The console should have a message like this in it:

Uncaught ReferenceError: ajaxRequest is not defined

I suggest reading up on the dev tools for your preferred browser.