Search code examples
srccreateelement

Load PHP file with document.createElement()


How could I make this work? I want to load a php file like this:

  • Click button.
  • Call Javascript function.
  • In Javascript function create an img with src file.php.

This should force the loading of the php. Here is the code.

<script type="text/javascript">
var d;

function callSave() {
 alert ('calling');
 if (d) document.body.removeChild(d);
 // d = document.createElement("script");
 d = document.createElement("img");
 d.src = "savepages.php";
 //d.type = "text/javascript";
 document.body.appendChild(d);
}

</script>

Then in savepages.php I do another alert to verify that the php is called and it isn't. Here is the savepages.php.

<?php
echo "alert('from the php');"; 
?>

The alert from the php doesn't happen. Is there a different element type that will force loading of the php? I don't have ajax installed, so I need a workaround like this.

Thanks.


Solution

  • Found out the better way to handle this. There is this simple code that explains how to call a javascript function from a form event and from that javascript function load a PHP file. The code found at http://daniel.lorch.cc/docs/ajax_simple/ is also given here:

    <script type="text/javascript">
    var http = false;
    
    if(navigator.appName == "Microsoft Internet Explorer") {
      http = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
      http = new XMLHttpRequest();
    }
    
    function validate(user) {
      http.abort();
      http.open("GET", "validate.php?name=" + user, true);
      http.onreadystatechange=function() {
        if(http.readyState == 4) {
          document.getElementById('msg').innerHTML = http.responseText;
        }
      }
      http.send(null);
    }
    </script>
    
    <h1>Please choose your username:</h1>
    
    <form>
      <input type="text" onkeyup="validate(this.value)" />
      <div id="msg"></div>
    </form>
    

    validate.php

    <?php
    function validate($name) {
      if($name == '') {
        return '';
      }
    
      if(strlen($name) < 3) {
        return "<span id=\"warn\">Username too short</span>\n";
      }
    
      switch($name) {
        case 'bob':
        case 'jim':
        case 'joe':
        case 'carol':
          return "<span id=\"warn\">Username already taken</span>\n";
      }
    
      return "<span id=\"notice\">Username ok!</span>\n";
    }
    
    echo validate(trim($_REQUEST['name']));
    ?>