1

I have a problem with dynamic loading of javascript function from Ajax. I want to update some part of HTML with Ajax. Let's say I want to place a button and to attach a javascript function to that button dynamically. For example: ...

<head>

<script src="ajax.js" type="text/javascript"></script>

<script type="text/javascript">
function f_OnLoadMain()
{
fParseBrowserInfo();
getJSFromServer();
getHTMLFromServer();

}
</script>
</head>

<body onload="f_OnLoadMain()">
<div id="AjaxArea" width="100%" height="100%" align="left" valign="top" >
<!-- Updated with ajax -->
</div>
</body>
</html>

----- getJSFromServer() - calls to php code:

<?php
$somesource = '
function Clicked(){
    alert("Clicked");
}
';

class TestObject{
    public $source = "";

    function TestObject()
    {
        $this->source = "";
    }

    function setSource($source){
        $this->source = $source;
    }
}
$ti = new TestObject();
$ti->setSource($somesource);
echo(json_encode($ti));
?>

the script is inserted with:

var oHead = document.getElementsByTagName('HEAD').item(0);
if (oScript){ 
  oHead.removeChild(oScript); 
}
oScript = document.createElement("SCRIPT");
oScript.type = 'text/javascript';
oScript.text = oScript.source;
oHead.appendChild( oScript);

And getHTMLFromServer() - call php :

<?php
$error = 0;

$someText = '
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()"    value="SomeBtn">
';
class TestObject{
    public $src = "";
    public $error = 0;

    function TestObject()
    {
        $this->error = 0;
        $this->src = "";
    }

    function setSrcString($sample){
        $this->src = $sample;
    }
}
$ti = new TestObject();
$ti->error = $error;
$ti->setSrcString($someText);
echo(json_encode($ti));
 ?>

Then the content is updated with:

 var dynamicArea = document.getElementById("AjaxArea");
 if(dynamicArea != null)
 {
    dynamicArea.innerHTML = obj.src;
 }

And that works fine!

So, when the page loads the button is displayed ok, BUT pressing button doesn't call function Clicked().

Someone knows how to fix it?

Regards!

Bryan
  • 2,191
  • 20
  • 28

1 Answers1

0

i guess you have to escape your apostrophe:

<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()"    value="SomeBtn">

you see: onclick="Clicked()"

Together with: function Clicked(){ alert("Clicked"); }

It renders to: onclick="alert("clicked")"

Try to escape your apostrophe :)

Regards

Grrbrr404
  • 1,809
  • 15
  • 17
  • Problem solved. It seems that when I copy/paste the js function in php file some incorrect character were inserted... After retyping all works fine! – user1044708 Nov 14 '11 at 17:56