Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AJAX JavaScript problem

Status
Not open for further replies.

jessiema

Technical User
Sep 3, 2007
1
US
In AJAX, I need to return several javascript functions which are called by event handlers in the http response. However, I cannot get those javascript functions evaluated by the browser.

For example, if server returns the following for an AJAX request:

<script>
function foo()
{
}
<script>

<form>
<input type='button' value='test' onclick='foo()'> </form>

I can see the 'test' button, but when I click it, I got error: "foo() not defined".

I searched on google and found people suggested using eval(), but that doesn't work for function either.
 
I searched on google and found people suggested using eval(), [!]but that doesn't work for function either.[/!]

Sorry, but that's just not true. Your problem is that you're likely trying to eval everything that is returned by your ajax process (which includes script tags and other various html). You need to strip the javascript out of what is returned and eval that only.

For example, here I've built a string named a that contains <script> tags and some content in a <div> tag. I strip out the javascript using the split function and alert the results (just so that we can verify I've pulled out the javascript) and store it in a variable called b. I then eval the contents of b (the blah() function definition) and invoke the blah() function - which gives us the alert message as expected.

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>title test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">

var a = "<script";
a += ">function blah() {alert('this is a test')}</script";
a += "><div>this is a test</div>";

alert(a);

//here's the meat and potatoes:
var b = a.[!]split(/\<\/?script[^\<]*\>/i)[/!][0];

alert(b);

eval(b);

blah();

</script>

<style type="text/css"></style>
</head>
<body>
</body>
</html>

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson
 
you're welcome, glad I could help

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top