Creating an iframe in function and loading source

Hi:

I create an iframe in script and load it with this code.

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

function callSave() {
 alert ('calling');
 if (d) document.body.removeChild(d);
 d = document.createElement("iframe");
 //d.setAttribute('src', 'savepages.php');
 d.setAttribute('style', 'visibility: visible');
 d.src = "savepages.php";
 //d.type = "iframe";
 document.body.appendChild(d);
}

</script>

This should force the loading of the savepages.php file. In that file I do an echo to verify that it is called.

<?php
echo "from the savepages php"; 
?>

The objective is to call that php function. The javascript function is called. I don’t know if the element is actually created. Unlike php javascript doesn’t put anything in the source for us to verify.

I don’t have ajax. How can I make the javascript function call create an element that loads the php file and causes the code in that php file to execute.

I see one major reason why your not seeing anything on the page and that’s due to there been no width of height on the iframe, try the following code below and it should appear on the page.

var d;

function callSave() {
    var _body = document.getElementsByTagName('body')[0];
    alert('calling');
    if (d) _body.removeChild(d);
    
    d = document.createElement('iframe');
    d.style.visibility = 'visible';
    d.src = 'savepages.php';
    d.height = '200';
    d.width = '500';
    _body.appendChild(d);
}

PS: It’s also good practice to use document.[COLOR=Teal]getElementsByTagName/COLOR as its more cross browser friendly.

Hi:

I found a better way. This code from Simple AJAX Example is the better way.

<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('foo').innerHTML = http.responseText;
    }
  }
  http.send(null);
}
</script>

<h1>Please choose your username:</h1>

<form>
  <input type="text" onkeyup="validate(this.value)" />
  <div id="foo"></div>
</form>

validate.php

<?php
function validate($name) {
  if($name == '') {
    return '';
  }

  if(strlen($name) < 3) {
    return "<span id=\\"warn\\">Username too short</span>\
";
  }

  switch($name) {
    case 'bob':
    case 'jim':
    case 'joe':
    case 'carol':
      return "<span id=\\"warn\\">Username already taken</span>\
";
  }

  return "<span id=\\"notice\\">Username ok!</span>\
";
}

echo validate(trim($_REQUEST['name']));
?>