www.webdeveloper.com
Results 1 to 10 of 10

Thread: Ajax question - responseText return a javascript code but browser can't run it - help

  1. #1
    Join Date
    May 2006
    Posts
    31

    Ajax question - responseText return a javascript code but browser can't run it - help

    Hello!

    Please look at my code below

    File index.html
    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <TITLE> Test Ajax </TITLE>
    <script language=javascript>
    //============
    function createRequest() {
    	var request = null;
    	try {
    		request = new XMLHttpRequest();
    	} 
    	catch (trymicrosoft) {
    		try {
    			request = new ActiveXObject("Msxml2.XMLHTTP");
    		} 
    		catch (othermicrosoft) {
    			try {
    				request = new ActiveXObject("Microsoft.XMLHTTP");
    			} 
    			catch (failed) {
    				request = null;
    			}
    		}
    	}
    
        return request;
    
    }
    
    //============
    var request_call_alert = createRequest();
    function call_alert(){
    	url = "index.php";
    	request_call_alert.open("GET", url, true);
    	request_call_alert.onreadystatechange = call_alert2;
    	request_call_alert.send(null);
    }
    function call_alert2(){
    	if (request_call_alert.readyState == 4) {
    	    if (request_call_alert.status == 200) {
    			var result = request_call_alert.responseText;
    			document.getElementById("object").innerHTML = result;
    		}
    	}
    }
    
    </script>
    </HEAD>
    
    <BODY>
    
    <form>
    <div id=object></div>
    <input type="button" value="Call Ajax Alert" onClick="call_alert();">
    </form>
    
    </BODY>
    </HTML>
    And here is my PHP script
    index.php
    PHP Code:
    <?
    print "<b>Javascript Alert</b>";
    print 
    "<script language=javascript>alert('How to make this alert works?')</script>";
    ?>
    As you can see responseText will return the HTML code

    HTML Code:
    <b>Javascript Alert</b><script language=javascript>alert('How to make this alert works?')</script>
    So when I click button "Call Ajax Alert" , all I see is the text Javascript Alert - I don't see the pop up alert.

    I need your help to make this alert work.

    Thanks.
    Kevin

  2. #2
    Join Date
    Dec 2004
    Posts
    8,637
    The problem with JavaScript code, received via an Ajax call, is that it is received as a text string and I'm not aware of any formal method for telling the browser to invoke the JavaScript Engine and, thus, turn that text string into executable JavaScript code. Did you notice that I said "formal" method, though. The only "informal" method I'm aware of (that works) is using the eval() method.

  3. #3
    Join Date
    Feb 2006
    Location
    Where I live, people get shot. I need to move.
    Posts
    634
    eval() is a very useful and easily abused function.

    eval is your portal into the JScript / JavaScript engine, you poke it with VALID code and the interpreter will run that section of code, you can easily run into trouble with misuse of it, so you MUST limit its use and take care when using it...
    Code:
    var y = 'prompt("Hi what is your name?","");';
    var x = eval(y);
    document.write('Hello ' + x);
    If life gives you a hard knock once in a while, your lucky. All I keep getting is a savage beating... everyday!
    AJAX! - Javascript Sha1 & MD5 - ASCII tables - Zend DevZone - My Space
    Stop Badware - Create "TEXT FILE" in Javascript - . - wikipedia on PHP -

  4. #4
    Join Date
    May 2006
    Posts
    31
    Thanks for your reply. But I still can't make this alert work with eval().

    I modified my index.php script like this:

    PHP Code:
    <?php
    print<<<EOF
    <b>Call Alert</b>
    <script language=javascript>
    var y = 'prompt("Hi what is your name?","");';
    var x = eval(y);
    document.write('Hello ' + x);
    </script>
    EOF;
    ?>
    Any idea? Thanks

    Kevin

  5. #5
    Join Date
    Dec 2004
    Posts
    8,637
    What DOCTYPE are you using? Perhaps this:

    <script language=javascript>

    should be this:

    <script type="text/javascript">

  6. #6
    Join Date
    Feb 2006
    Location
    Where I live, people get shot. I need to move.
    Posts
    634
    I thought that you want a script returned by an AJAX request to be run in the browser.

    if you take the responseText value that is returned and pass it to eval() the script will run if the code is VALID!

    The example I p[osted was to demonstrate that the value in the string was script and that eval when it recieved it ran the script and returned a value.

    that should be more than enough for you to achieve your goal.
    If life gives you a hard knock once in a while, your lucky. All I keep getting is a savage beating... everyday!
    AJAX! - Javascript Sha1 & MD5 - ASCII tables - Zend DevZone - My Space
    Stop Badware - Create "TEXT FILE" in Javascript - . - wikipedia on PHP -

  7. #7
    Join Date
    Oct 2008
    Posts
    2
    Sorry to revive a VERY old topic, but it's relevant to my question:

    I'm doing pretty much what the rest of this thread is describing. Once I get the readyState == 4 and have my response rendered, I call a function that gets the elements with name "scripts" in my response and then passes the innerHTML to eval.
    This works if the innerHTML contains only alert("test"); but the problem is that it also prints the text "alert("test");" to the page, as well as evaluating it. If I wrap it in script tags it no longer print but doesn't execute either.

    What's the right way of executing the script code without printing it to the page.

    My response is from a PHP script.

  8. #8
    Join Date
    Sep 2006
    Location
    Copenhagen, Denmark
    Posts
    1,253
    The JavaScript code you recieve in responseText is just text. To have the browser interpret the responseText as JavaScript you need to eval it. Its very simple...you just do
    Code:
    if (xhr.readyState == 4)
      eval(xhr.responseText);
    An example of how eval works
    Code:
    // A string
    var s = 'function test(){alert("Hello world"};';
    // Now eval the string
    eval(s);
    // The function test is now available
    test();  // Output is 'Hello world'
    #define question (2B || !2B)
    HTMLElement and W3C Event Handling in IE
    My JavaScript Library

    Don't PM me about answers to questions. If I don't reply in a thread it's because:
    • You didn't read the message posting guidelines
    • Your code is too unstructured and/or formatted poorly - correcting it is too time consuming
    • I simply don't know the answer

  9. #9
    Join Date
    Oct 2008
    Posts
    2
    I wasn't clear enough in my previous post, sorry. The problem is that I want part of the response rendered on the page, as well as some javascript on the page as well, that is generated from the PHP.

    I got this working by wrapping the script sections in tags and then evaluating only those bits of the response, and then additionally also setting the display style to 'none' to stop it printing. If I don't set it to display:none then the script sections get evaluated by eval AND get printed on the page

    I'm not sure this the correct way of doing it, but the results are what I need.

  10. #10
    Join Date
    Sep 2006
    Location
    Copenhagen, Denmark
    Posts
    1,253
    I would recommend using 2 separate requests but if you insist on 1 then do something like
    Code:
    var s = '<div>some html</div>[JS]function test(){some JS}';
    // Split the string at [JS]
    var s = s.split('[JS]');
    Now s[0] is the HTML and s[1] is the javascript.
    #define question (2B || !2B)
    HTMLElement and W3C Event Handling in IE
    My JavaScript Library

    Don't PM me about answers to questions. If I don't reply in a thread it's because:
    • You didn't read the message posting guidelines
    • Your code is too unstructured and/or formatted poorly - correcting it is too time consuming
    • I simply don't know the answer

Thread Information

Users Browsing this Thread

There are currently 2 users browsing this thread. (0 members and 2 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles