tags:

views:

109

answers:

1

Still stuck on my PHP calling a JS script problem

On the click of a button this Javascript is called:

var xmlhttp;
function register()
{   
 xmlhttp=GetXmlHttpObject();
 alert("pass");
 if(xmlhttp==null)
 {
  alert("Your browser does not support AJAX!");
  return;
 }
 var url="register.php";
 url=url+"?id="+uniqueid+"&name="+name+"&passwrd="+passwrd1+"&email="+email;
 xmlhttp.onreadystatechange=statechanged;
 xmlhttp.open("GET", url, true);
 xmlhttp.send(null); 
}

function statechanged()
{
    //alert("statechanged function");
    if(xmlhttp.readyState==4)
    {
     //alert(xmlhttp.responseText);
     document.getElementById("response").innerHTML=xmlhttp.responseText;
    }
}

function GetXmlHttpObject()
{
    if(window.XMLHttpRequest)
    {
     return new XMLHttpRequest();
    }
    if(window.ActiveXObject)
    {
     return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}

function testing()
{
    document.getElementById("mainbody").innerHTML="This is my first JavaScript!";
}

And then this PHP script is called:

<?php
    echo "<script type=\"text/javascript\">testing();</script>";
?>

The HTML has two DIV tags with IDs of mainbody and response:

<HTML>
<HEAD>
<SCRIPT SRC=javascriptname.js></SCRIPT>
</HEAD>
<BODY>
  <DIV ID=mainbody>
     <DIV ID=response>
     </DIV>
  </DIV>
</BODY>
</HTML>

I am unable to call the javascript from my php. If anyone know what am i doing wrong, or has a idea what should i do, it will be very helpful.

Thank you Zeeshan

+2  A: 

I don't think changing the innerHTML of an object and inserting a script will cause it to fire. I certainly wouldn't want to depend on that behavior.

Why not just do some kind of string comparison on the responseText, (in a case statement, for example) and then call the appropriate function?

EDIT: You could also remove the script tags, and call eval on the responseText, but eval is not the nicest function in the world.

Dave
Well i was thinking of the same, but it will not be a very good way as per my code requirement. it would be my last option
Zeeshan Rang
I agree, the script will not fire on a dynamic update. Any way you can change your quite odd code requirement?
David Archer
what i am doing is, creating a register form, if there are errors i show it in the response div tag, and if there are no errors, i want to show the result in mainbody div tag. do you think there is some other way i should do it??
Zeeshan Rang
If you really want a script tag in your DOM, you could create one via document.createElement, set the innerHTML to your your response text (like 'testing()') and then put it in your head. All done in your statechanged function. But that's essentially eval....and what I'm suggesting is just weird.
seth