0

I'm using PHP to populate an HTML table with random numbers on page load. When button is clicked, I want to re-populate the table with new numbers by calling PHP via an ajax request. Problem is I can't use (or at least really want to avoid using) external files : PHP must be called via ajax request in the same file.

File is index.php and contains following simplified PHP code :

<?php 
    //code to be executed via ajax call should be placed here ?
?>
<!DOCTYPE html>

<HTML>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
<HEAD>
    <title>PHP test</title>
</HEAD>

<BODY>
  <table id="table"> 
    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '<tr>';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo '<td>'. $values[$v] .'</td>';
      }
      echo '</tr>';
   ?>
  </table>

  <button id="btn">Generate new numbers</button>
<BODY>

Here is my current ajax request :

<script type="text/javascript">
function send_ajax() {
  console.log('btn clicked');
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest(); //code for IE7+, Firefox, Chrome, Opera, Safari
  }
  else {
    xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); //code for IE6, IE5
  }
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log('data sent');
    }
  }
  xmlhttp.open('POST', 'index.php', true);
  //xmlhttp.send(document.getElementById('input').value);
}

document.getElementById('btn').addEventListener('click', send_ajax, false);
</script>

I'm sure I'm missing something obvious, but I have no idea how I should adapt my php code and ajax request to repopulate the table when receiving ajax call in the same file.

(Note : I know it would be very easy using external files, but this scenario is a typical example of what I need to do with ajax and PHP for more complex tasks over dozens of different files).

1
  • Why don't you make the page is loaded with empty table then initialize the ajax request that fills this table ? Commented Mar 31, 2017 at 20:38

2 Answers 2

1

How about something like this ...

<?php 
    if($_GET['load']) {

          $howMany = 10;

          $values = array();

          echo '<tr>';
          for ($v = 0; $v < $howMany; $v++) {
            $values[$v] = mt_rand(-10, 10);
            echo '<td>'. $values[$v] .'</td>';
          }
          echo '</tr>';    

    } else {
?>
<!DOCTYPE html>

<HTML>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
<HEAD>
    <title>PHP test</title>
</HEAD>

<BODY>
  <table id="table"> 
    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '<tr>';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo '<td>'. $values[$v] .'</td>';
      }
      echo '</tr>';
   ?>
  </table>

  <button id="btn">Generate new numbers</button>
</BODY>
<?php } ?>

And then ...

xmlhttp.open('GET', 'index.php?load=1', true);

This could definitely be improved but the concept I've outlined is how I would approach your challenge.

Sign up to request clarification or add additional context in comments.

1 Comment

Just got your solution to work. Using your idea with different configurations taught me a lot about how ajax and php communicate and work together. Thank you
1

you can check for isset($_POST['variable']) and return data in json format

e.g

<?php 
    //code to be executed via ajax call
  if(isset($_POST['query']) && $_POST['query'] != "")
   {
       return json_encode(mt_rand(-10, 10));
   }
?>
<!DOCTYPE html>

<HTML>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
<HEAD>
    <title>PHP test</title>
</HEAD>

<BODY>
  <table id="table"> 
    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '<tr>';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo '<td>'. $values[$v] .'</td>';
      }
      echo '</tr>';
   ?>
  </table>

  <button id="btn">Generate new numbers</button>
<BODY>

//here is the ajax code

<script type="text/javascript">

    function send_ajax() {
      console.log('btn clicked');
      if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest(); //code for IE7+, Firefox, Chrome, Opera, Safari
      }
      else {
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); //code for IE6, IE5
      }
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          console.log('data sent');
        }
      }
      xmlhttp.open('POST', 'index.php', true);
      var data = new FormData();
      data.append('query',document.getElementById('input').value);
      //you can append more data in same manner for sending more data 
      xmlhttp.send(data);
    }

    document.getElementById('btn').addEventListener('click', send_ajax, false);
    </script>

5 Comments

hope you get the logic and instead of return one value you can return any thing by using json_encode function
Thank you ! I get the logic behind the json_encode but I can't get the ajax call to trigger your PHP if condition (although the ajax call itself is working). I guess my problem is to get a real understanding of the logic behind the ajax calls.
@Hal_9100, i have updated the answer, hope you will get it
Just got it to work ! I actually used both your answer and chris' to make it work, but it really gave me a better understanding of ajax and json for data exchange. Thank you !
Thank you @Hal_9100

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.