0

I want php to return a value to ajax. I'm following W3 schools example but no joy. Here is the javascript/ajax code:

function createReport() {
    var xmlhttp;    
    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("report").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","test.php",true);
    xmlhttp.send();
}

I have the following call inside an event handler that I know is triggering (other stuff it does is working fine)

createReport();

and later in the body section of the html I have:

<div id="report">Report will be placed here...</div>

If I run test.php by itself, it correctly shows "return this to ajax" so I know that's working. Here is the php code:

<?php
echo 'return this to ajax';
?>

My understanding is that "Report will be placed here..." will be replaced with "return this to ajax". But nothing happens. I don't see any errors listed in the firefox or IE consoles either. Any ideas?

user3217883
  • 1,216
  • 4
  • 38
  • 65
  • Is very likely to be the order that you set up that is a problem in the treatment of HTTP errors. See my answer: http://stackoverflow.com/a/21387485/1518921 – Protomen Jan 27 '14 at 17:30

5 Answers5

2

I personally do not think the w3cschools a good place to learn ( see http://www.w3fools.com/ ).

It may be that the problem occurs because of the order that you set the ajax, you did:

XMLHttpRequest/onreadystatechange/open/send

is preferable (if you do not follow this order may occur several flaws in older browsers):

XMLHttpRequest/open/onreadystatechange/send

Note: do not worry, the "open(...)" does not start listeners. Listeners only work after the "send(...)"

Another reason may be that you did not create "error handling" of XMLHttpRequest.status, it serves to verify faults in the server response.

Try this:

<script>
function XHR(){
    if(window.XMLHttpRequest){//outers browsers
        return new XMLHttpRequest();
    } else if(window.ActiveXObject){//IE
        try{
            return new ActiveXObject("Msxml2.XMLHTTP");
        } catch(ee) {//IE
            try{
                return new ActiveXObject("Microsoft.XMLHTTP");
            } catch(ee) {}
        }
    }
    return false;
}

function createReport(){
    var xhr = XHR();// call ajax object
    if(xhr){
        xhr.open("GET", "test.php", true);//setting request (should always come first)
        xhr.onreadystatechange = function(){//setting callback
            if(xhr.readyState==4){
                if(xhr.status==200){
                    document.getElementById("report").innerHTML=xhr.responseText;
                } else {//if the state is different from 200, is why there was a server error (eg. 404)
                    alert("Server return this error: " + String(xhr.status));
                }
            }
        };
        xhr.send(null);//send request, should be the last to be executed.
    } else {
        alert("Your browser no has support to Ajax");
    }
}
</script>

<div id="report">Report will be placed here...</div>

<script>
createReport();//prefer to call the function after its div#report
</script>

To prevent cache, replace:

xhr.open("GET", "test.php", true);

by

xhr.open("GET", "test.php?nocache="+(new Date().getTime()), true);

Protomen
  • 9,471
  • 9
  • 57
  • 124
  • "w3schools" that place should not even exist. – Jorge Faianca Jan 27 '14 at 17:31
  • I didn't mean your typo, i'm glad that you did the typo, my point was, "w3schools" shouldn't exist, it's bad and no one should learn from that website. – Jorge Faianca Jan 27 '14 at 17:35
  • `is preferable: xhr, open , onreadystatechange and send.` nope. a right way is to put the listener before you open the link. even though this looks procedural, the listener will listen even if the open is made after. I use op's order in each of my ajax calls and this has never been a problem. here this guy explains it better: http://stackoverflow.com/questions/16848955/ajax-onreadystatechange-open-send-order-totally-arbitrary – Félix Adriyel Gagnon-Grenier Jan 27 '14 at 17:45
  • @FélixGagnon-Grenier the reason is because of failure in some browsers, note that "onreadystatechange" only starts working after "send()", then "open/onreadystatechange" or "onreadystatechange/open" would not change anything. But the problem is some older browsers, eg. IE7 (as is the link you sent me own ). Thanks anyway, share experiences is cool – Protomen Jan 27 '14 at 18:02
1

At first glance I don't see anything wrong on your js code, so I bet it will probably be a problem locating test.php in your folder structure.

With firebug check the call your javascript AJAX it's doing, and check if the file test.php is being correctly assesed.

Bardo
  • 2,470
  • 2
  • 24
  • 42
0
try{
    request = new XMLHttpRequest();
}catch(trymicrosoft){
     try{
        request = new ActiveXObject("Msxml2.XMLHTTP");
     }catch(othermicrosoft){
        try{
            request = new ActiveXObject("Microsoft.XMLHTTP");
       }catch(failed){
            request = false;
       }  
    }
}
if(!request)
{
    alert("Error initializing XMLHttpRequest!");
}

function Create_Ajax_Query(LinkToFile,Parametrs)
{
    window.document.body.style.cursor='progress';
    request = new XMLHttpRequest();
    var url = LinkToFile;
    var params = Parametrs;

    request.open("POST", url, true);    
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
    request.setRequestHeader("Content-length", params.length);
    request.setRequestHeader("Connection", "close");
    request.onreadystatechange = newinfo;
    request.send(params); 
 }

function newinfo() 
{
    if(request.readyState==4 && request.status == 200){
        window.document.body.style.cursor='default';
        alert(request.responseText);
    } 
}

Hope its useful!

Arthur Yakovlev
  • 8,933
  • 8
  • 32
  • 48
0

I did not find anything wrong with W3Schools' Ajax example, after testing the code that follows (which was pulled from their Website).

  • Possible factors:

    1. Missing <script></script> tags

    2. Make sure you have JS enabled.

    3. Make sure your browser supports it.

    4. You may have forgotten to change the button's call to the proper function.

Working and tested code using FF 26.0 and IE version 7

Pulled from W3 Schools Website (example) and slightly modified to prove this works.

Result when clicking on the Change Content button:

return this to ajax - as per your PHP code.

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
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("report").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="report"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

PHP used: (test.php)

<?php
echo 'return this to ajax';
?>

  • Other possible factors:

    1. If on a local machine, your server doesn't support PHP or is not parsing PHP properly, or is either not installed or configured properly.
    2. If on a hosted service, make sure PHP is available for you to use.
    3. Files are not in the same folder as executed from.
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • I copied this exactly and put it into a new file and uploaded to the server. You're right, it does work! Still can't get it to work in my code though so I'm doing something wrong. This narrows my search considerably. Looking for differences now... Yes, I have script tags. – user3217883 Jan 27 '14 at 18:05
  • Why don't you use my code and replace all instances of `loadXMLDoc()` with what you have `createReport()` ? @user3217883 - It'll basically be `plug & play` ;-) – Funk Forty Niner Jan 27 '14 at 18:06
  • I also just tested it now on `IE 7` and it worked for that browser also. @user3217883 - Which browser and version are you using? And make sure your `div id` matches. – Funk Forty Niner Jan 27 '14 at 18:09
  • Making any progress? @user3217883 – Funk Forty Niner Jan 27 '14 at 18:33
  • sorry-got delayed by long phone call... I added following code to make sure there are no folder issues: alert('im in createReport'); xmlhttp.open("GET","http://virtualhuman.tekknow.net/test.php",true); xmlhttp.send(); alert('back from send'); Both alerts are displayed but still the div id=report does not change its contents – user3217883 Jan 27 '14 at 18:56
  • I think the `alert`'s may be causing an issue. @user3217883 - and just using `virtualhuman.tekknow.net/test.php` instead of `http://virtualhuman.tekknow.net/test.php` could also be at play. – Funk Forty Niner Jan 27 '14 at 19:01
  • Well I got it working. I basically kept the test file and gradually added back in more code. I was hoping to find what additions would cause it to stop working but it kept working all the way until it was identical to what I had before! So no satisfying answer as to why it wasn't working before. Thanks to all who contributed. Can't believe how gracious and generous you all were with your time. I will try to reciprocate in the future. – user3217883 Jan 27 '14 at 20:03
  • I'm glad it was resolved, however no so good when it's not running the way it was planned. The best advice I can give is to do just what you've done, step-by-step to see what is interferring. @user3217883 – Funk Forty Niner Jan 27 '14 at 20:09
0

The code looks correct. it runs just fine on a local environment. I would advise to look at the "Network" tab in the developer tools to detect any errors may occurs on the server side. You can also use console.log() to follow the javascript actual flow:

function createReport() {
    var xmlhttp;    
    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() {
        console.log(xmlhttp); //to show the entire object after statechage.
        console.log(xmlhttp.readyState); //to show specific parameter.        

        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("report").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","test.php",true);
    xmlhttp.send();
} 
Mutale
  • 310
  • 1
  • 8