-1

I'm trying to run a PHP code by the click of a button, but it does not seem to work. I'm running this on a MAPM server.

<html>
    <head>
    </head>
    <div onClick="count();">Click!</div>
    <script>
function count() {
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.open('GET', 'count.php');
    xhr.send();
}​
    </script>

    </body>
</html>

In the PHP file (count.php) we have this code:

<?php
Print "Hello, World!";
?>
2
  • Is the URL correct? or will it be "/count.php"? Commented Jun 17, 2012 at 9:48
  • 3
    What do you mean by "does not seem to work"? The script has no side effects and you're not doing anything with the output, so nothing would happen even if the request succeeded. Is this the real code? Commented Jun 17, 2012 at 9:48

2 Answers 2

2

you need your page to listen to the request;

function count() {
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.onreadystatechange =     function (){
    if(xhr.readyState == 4){
        if(xhr.status == 200){
            // WHAT HAPPENS ON SUCCESS
            alert(xhr.responseText);
        }else{
                alert('timeout error or something');
        }
        }
    };
    xhr.open('GET', 'count.php');
    xhr.send();
}​;
Sign up to request clarification or add additional context in comments.

Comments

0

You need to pass null to the send() method like below (also be sure that the URL is correct, my hunch is that it should be "/count.php"):

xhr.send(null) // it's a GET request

For a detailed tutorial, check out this MDN doc https://developer.mozilla.org/en/AJAX/Getting_Started

3 Comments

Pass "true" as the third parameter to your xhr.open() call, like this xhr.open('GET', '/count.php', true);
Okay, if you have Firebug or Chrome Developer Tools, can you inspect and see what are you getting as the response status of your request? If it is 404 then the URL is not correct, if the response is 200 then it is working (your PHP code is working fine), if it is 500 then there's an exception on your server, please dig further into it.
Nothing happens. I have no idea why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.