PHPeter
PHPeter

Reputation: 77

Data output using Ajax with PHP

I will break this question into paragraphs for easier reference.

  1. I have a script that calls a php file using Ajax; the script is executed once a button is pressed.

  2. The PHP file contains a simple code that plusses a number with 1.

    <?php 
    $response = $response + 1;
    echo $response;
    ?>
    
  3. However, something goes wrong when the button is pressed multiple times. I have done some research and I can conclude that there is either something wrong with the simple PHP script that I have made, or the code is only executed once per page reload.

  4. I read an article explaining a lot of work using Javascript if I want an Ajax command to execute multiple times during the same script but I don't see the reason that it can't execute multiple times already when the button is pressed.

    Question: Is the PHP file "post.php" even getting executed everytime the button is pressed? Is it something with my PHP file? How can I make the script plus the number by 1 everytime the button is pressed? And is it because I need some extra Javascript to do that?

The rest of the script is here:

 <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("myDiv").innerHTML=xmlhttp.responseText;
            }
          }
        xmlhttp.open("POST","post.php",true);
        xmlhttp.send();
        }
    </script>

</head>
<body>
    <p>This button will execute an Ajax function</p> 
    <button type="button" onclick="loadXMLDoc()">Press here!</button>
    <div id="myDiv"></div>
    <script type="text/javascript" src="http://www.parameter.dk/counter/5b0d9873158158e08cad4c71256eb27c"></script>
</body>

If I wasn't clear enough at some point, please pick out the paragraph number and I'll deepen that part.

Upvotes: 1

Views: 145

Answers (1)

jcubic
jcubic

Reputation: 66478

In your code $response is always 1 because php by default have no state. You can fix it by saving response inside a session.

session_start();
if (isset($_SESSION['response'])) {
    $_SESSION['response'] = $_SESSION['response'] + 1;
} else {
    $_SESSION['response'] = 1;
}
echo $_SESSION['response'];

Upvotes: 1

Related Questions