简体   繁体   中英

ajax php call not returning anything

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?

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);

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.

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!

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.

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();
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM