0

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

3 Answers 3

1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

another approach: using eval

var result = ajaxResponseText;// "alert('hi')"; in your case
eval(result);

2 Comments

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
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
0

You must create script tag with returned data;

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.