Javascript in PHP called via AJAX does not occur

advertisements

I am using a YUI Rich Text Editor and saving the entered text into a database. Since the user can enter several different texts, I am using a drop down to let them choose an existing database entry to edit, or create a new one. To do this I call a JS function that handles AJAX, use that to get the information from the database, and then display the returned information.

The PHP code that is called is:

$query = "SELECT * FROM tableName WHERE id='".mysql_real_escape_string($_POST['id'])."'";
$result = mysql_query($query) or die(mysql_error());
$data = mysql_fetch_assoc($result);
echo "<script type='text/javascript' language='JavaScript'>
alert('HEY HEY HEY'); //Just to see if JS is happening at all
document.getElementById('saveName').innerHTML = '$data[name]';
document.getElementById('editor').innerHTML = '$data[content]';
document.getElementById('editID').value = '$data[id]';
</script>";

When I change the select box no errors are thrown, and Firebug reports that the AJAX was successful (POST 200 OK) and the response is what I expect:

<script type='text/javascript' language='JavaScript'>
alert('HEY HEY HEY');
document.getElementById('saveName').innerHTML = 'Default';
document.getElementById('editor').innerHTML = 'REALLY LARGE BLOB OF TEXT';
document.getElementById('editID').value = '1';
</script>

But the alert never happens and the inner HTML doesn't change. Can you not call javascript like this from a PHP page loaded by AJAX?


You should be able to load stuff into the DOM dynamically with PHP/AJAX/Whatever. What you can't do is to modify HTML elements dynamically loaded in to the DOM without running some soft of LiveQuery (like the live command in jquery). However, sometimes the execution of dynamically loaded stuff from javascript simply wont work.

In which context do you load this script? It may work do define functions who's loaded at runtime, then you simply call them with your php generated code.

In example, put this inside your head tag

<script>
function sendAlert(input) {
   alert(input);
}

function changeInnerHtml(id,innerContent) {
   document.getElementById(id).innerHTML = innerContent;
}

function changeInnerValue(id,innerValue) {
   document.getElementById(id).value = innerValue;
}
</script>

And try to change your php code to

$query = "SELECT * FROM tableName WHERE id='".mysql_real_escape_string($_POST['id'])."'";
$result = mysql_query($query) or die(mysql_error());
$data = mysql_fetch_assoc($result);
echo "<script>
sendAlert('HEY HEY HEY');
changeInnerHtml('saveName', '$data[name]');
changeInnerHtml('editor', '$data[content]');
changeInnerValue('editID', '$data[id]');
</script>";

Not sure if it will resolve your problem but it might be worth a try :)