views:

81

answers:

3

Hi guys, I was playing around with AJAX.

If I do

echo "helllo"

in the PHP file it works fine.

However, if I do something like

echo "<script language=Javascript> alert('hi');</script>";

in the PHP file, the alert() does not come up.

Anyone know if I'm doing anything wrong?

example:

in my html file i've got this

<div id='something'> </div>

and i want the response text from the php file be placed above:

if (req.status==200) {
     document.getElementById('something').innerHTML=req.responseText;
}

if i changed that to:

if (req.status==200) {
     document.getElementById('something').innerHTML="<?php echo 'hi';?>";
}

it works fine, the response text will be ---> hi
but if i do echo "\"<?php echo 'hi';?>\""; in my php file, the response text will be ""

i hope i was clear in explaining

A: 

another approach: using eval

var result = ajaxResponseText;// "alert('hi')"; in your case
eval(result);
jebberwocky
This is awful to teach someone learning.
alex
i answered this when Sunny didn't post this code. how do i know ? just providing another way to play around with javascript. i don't see what wrong with exploring new thing
jebberwocky
I don't understand why people downvote each and every answer that contains the word `eval`. OK, `eval` can be dangerous but 1) it does work 2) there no 100% safe way to do what the OP is asking (this is as good -or as bad- as adding a script tag for instance) 3) if you have the control of what the PHP returns then there is not very much to worry about
nico
A: 

You must create script tag with returned data;

var script = document.createElement('script');
stript.innerHTML = req.responseText;
document.getElementsByTagName('head')[0].appendChild(script);
jcubic
+1  A: 

Hi,

use $.load() , and the script will be evaluated.

$("#something").load("request.php");

Maybe jQuery there also uses eval() , so it is'nt more safe, but as long as load() only works on the same Domain u should have Control over the things that will be evaluated.

However, it is easier to use, because you did'nt have to parse the Fragment for script's on your own :)

Dr.Molle
thanks for that!!!!
Sunny