/    Sign up×
Community /Pin to ProfileBookmark

Using eval() with ajax response

I am wondering how possible it is to use eval() to parse javascrpt that is pulled in through ajax(innerHTML)? I have found a few notes about this, such as:

[CODE]var myObj = eval ( xmlhttp.responseText );[/CODE]

I am confused on how to get this working…any ideas, or someone who has done this?

to post a comment
JavaScript

15 Comments(s)

Copy linkTweet thisAlerts:
@Angry_Black_ManApr 04.2008 — it is necessary to understand that the responseText property simply contains text. it isnt "HTML", it isnt "javascript", it isnt an object; it isnt anything except text.

because it is just text, you can stick it as the innerHTML property of an element, you can eval it, or you can stuff it into a variable. but again, this is just text. you have to ensure whatever you do with it is valid for whatever youre doing with it.

so for instance, lets say we did an ajax request. and that the "responseText" property of the "xmlhttp" object was as follows:

<font size=5>hello world</font>

remembering that payload this is just plain text, you could do any of the following, even stuff that doesnt work:

alert(xmlhttp.responseText)

response = xmlhttp.responseText.indexOf("lo worl")

// would error because this plain text isnt valid javascript syntax
eval(xmlhttp.responseText)


// stuff the response into an array using shorthand
var myArray = [xmlhttp.responseText]


<i>
</i>// in this example, assume that the responseText property contains only the word "myDiv"
// if myDiv exists as an object in the DOM, we could create an object reference with the responseText
var myObj = document.getElementById(xmlhttp.responseText)


so, now having hammered the point that responseText is just TEXT, you can do anything you want with it as long as it is valid for the method you choose, wether it be an eval, innerHTML, or whatever.
Copy linkTweet thisAlerts:
@nnhubbardauthorApr 04.2008 — Interesting. So, basically if it is mixed HTML and javascript, I am out of luck for actually parsing that javascript if it is in the response text, using eval()?
Copy linkTweet thisAlerts:
@KorApr 04.2008 — it is necessary to understand that the responseText property simply contains text. it isnt "HTML", it isnt "javascript", it isnt an object; it isnt anything except text.[/QUOTE]

eerrr, not really. The responseText [I]might[/I] be a "JSON like" written text, case in which eval() will transform the string text response into a [B]JSON object[/B]...
Copy linkTweet thisAlerts:
@nnhubbardauthorApr 04.2008 — eerrr, not really. The responseText [I]might[/I] be a "JSON like" written text, case in which eval() will transform the string text response into a [B]JSON object[/B]...[/QUOTE]

Kor,

I have also been reading about JSON, but am not sure how to use it. So, are you saying that it is possible to evaluate the response text even if it is mixed HTML and javascript, and still parse the javascript, using JSON? If so, how is this done?

Thanks so much!
Copy linkTweet thisAlerts:
@Declan1991Apr 04.2008 — eval pretends there never was a variable there, to put it simply. So basically:[code=php]
var object = '{"hello":"test"}';
var json = eval(object);
[/code]
is the exact same as[code=php]
var json = {"hello":"test"};
[/code]
Copy linkTweet thisAlerts:
@nnhubbardauthorApr 04.2008 — eval pretends there never was a variable there, to put it simply. So basically:[code=php]
var object = '{"hello":"test"}';
var json = eval(object);
[/code]
is the exact same as[code=php]
var json = {"hello":"test"};
[/code]
[/QUOTE]


Declan, could you explain a little more how to use this? How would this work with the response text?
Copy linkTweet thisAlerts:
@Angry_Black_ManApr 04.2008 — eerrr, not really. The responseText [I]might[/I] be a "JSON like" written text, case in which eval() will transform the string text response into a [B]JSON object[/B]...[/QUOTE]

i never said that the text inside of the responseText couldnt be FORMATTED in some way (which is why i illustrated that the text in the response could be HTML [I]formatted[/I]). but regardless of the way the text is formatted, it is nothing but text until you do something with or to it.

so it MIGHT be any million number of things. hell, it might be the source for PDF file. but no matter how you cut it, it is just a text string to "responseText".

i think one thing i never made clear is that the illustrations i provided are non-inclusive. anything that javsacript can do with text, you can do on your responseText, expected results or not. im simply saying that the STATE of that text is not "javsacript" (or an object therein), "html", or even "css". the STATE is text. however, the means of utilization of that text are endless as long as you properly [I]utilize[/I] the text that has been returned.

...eval() will [COLOR="Red"]transform the string text[/color] response into a [B]JSON object[/B]...[/QUOTE]

my point exactly. you've clearly reillustrated what i said.
Copy linkTweet thisAlerts:
@Angry_Black_ManApr 04.2008 — So, basically if it is mixed HTML and javascript, I am out of luck for actually parsing that javascript if it is in the response text, using eval()?[/QUOTE]

that is correct. using javascript fundamentals, you cant eval HTML formatted information. assuming that your response text contained the following:

xmlHttp.responseText = "[COLOR="Red"]&lt;[/COLOR]font color=red&gt;hello world&lt;/font&gt;&lt;script&gt;alert('hello world')&lt;/script&gt;"

trying to eval this would lead to an error because no javascript begins with a "<" character.

.... however, that doesnt mean the game is over. using a carefully formatted regular expression, you can find any information between <script> and </script>, insert it into a "evalable" variable (minus the script tags) and then fire it whenever you want during javascript execution.
Copy linkTweet thisAlerts:
@Angry_Black_ManApr 04.2008 — sorry to threadbload, but heres something i dug up with a search. i cant confirm that it works as written, but it basically illustrates how to parse the responseText and do what you need to do with the javascript portion. the "content" parameter would be your responseText property. instead of evaling, it uses the more elegant solution of createElement/appendChild which will do the exact same thing as evaling.

function sethtml(div,content)
{
var search = content;
var script;

<i> </i>while( script = search.match(/(&lt;script[^&gt;]+javascript[^&gt;]+&gt;s*(&lt;!--)?)/i))
<i> </i>{
<i> </i> search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length);

<i> </i> if (!(endscript = search.match(/((--&gt;)?s*&lt;/script&gt;)/))) break;

<i> </i> block = search.substr(0, search.indexOf(RegExp.$1));
<i> </i> search = search.substring(block.length + RegExp.$1.length);

<i> </i> var oScript = document.createElement('script');
<i> </i> oScript.text = block;
<i> </i> document.getElementsByTagName("head").item(0).appendChild(oScript);
<i> </i>}

<i> </i>document.getElementById(div).innerHTML=content;
}
Copy linkTweet thisAlerts:
@dctmuserMay 12.2008 — Hi

I am using eval function to evaluate an ajax response which is nothing but result of a query.

The problem I am facing is that when the result set contains french charachters,eval function breaks.

How can i handle these special charachters in eval??
Copy linkTweet thisAlerts:
@cessnapilotMay 19.2009 — I registered just to say... aaron.martinas, you sir, are the man and I thank you! I've spent countless hours looking for such an elegant solution to handling javascript from within my ajax response and never thought of a script to dynamically put it in the head of the page. May a beverage of your choice always fill your glass!
Copy linkTweet thisAlerts:
@Angry_Black_ManMay 19.2009 — haha, good times (:
Copy linkTweet thisAlerts:
@rnd_meMay 21.2009 — Hi

I am using eval function to evaluate an ajax response which is nothing but result of a query.

The problem I am facing is that when the result set contains french charachters,eval function breaks.

How can i handle these special charachters in eval??[/QUOTE]


you must not have valid JSON then.

JSON supports unicode, so i would imagine there's something wrong with the source.

where is the JSON coming from?
Copy linkTweet thisAlerts:
@Angry_Black_ManMay 22.2009 — unfortunately, the post you're referring to was a year ago (:
Copy linkTweet thisAlerts:
@abmitraOct 14.2010 — After long days of googling around and trying head and tail with eval() aaron.martinas's post saved my code. Though this is an age old post, but honestly this is the best, perfect and rarest of the solution provided anywhere around in the forums.

Thanks a lot for the perfect way to get Javascript working from Ajax response!
×

Success!

Help @nnhubbard spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...