2

Using Ajax, I'm calling a php file that contains javascript, but in this way, the javaScript doesn't work.

The main.html file is given here. It just uses Ajax for calling a php file called test1.php for updating all page at client.

 <!DOCTYPE html>
 <html>
 <body>
       <!-- run php file to fill the page -->
       <script>
             var xmlhttp = new XMLHttpRequest();

             xmlhttp.onreadystatechange=function()
             {
                 if (xmlhttp.readyState==4 && xmlhttp.status==200)
                 {
                    document.body.innerHTML = xmlhttp.responseText;         
                 }
             }

             xmlhttp.open("GET","test1.php",true);
             xmlhttp.send();
       </script> 
 </body>
 </html>

And the test1.php file is very simple test as follows:

 <p id="demo">Hi there</p>
 <script>
        document.write("Yes! Hi there");    
        alert('Welcome!');
 </script>

Now, just for checking that test1.php is ok, I put in the browser's url line:

localhost/test1.php

and everything works ok, the text of the html and js are displayed and an alert window with the word Welcome! is displayed.

But if I call the main page

localhost/main.html

Then only the html text 'Hi there' is displayed. The JS is ignored.

Anybody knows why is this? Thanks

user3198805
  • 103
  • 1
  • 6
  • It should works with an append instead giving that to the innerHTML. Append will append that as HTML and the js should be execute. Quentin is right, that thread has the solution. – fray88 Jan 28 '14 at 16:53

4 Answers4

1

Krasimir Tsonev has a great solution that overcome all problems. His method doesn't need using eval, so no performance nor security problems exist. It allows you to set innerHTML string contains html with js and translate it immediately to an DOM element while also executes the js parts exist along the code. short ,simple, and works exactly as you want. So in this case, the response from ajax is the src string which then translated to a DOM object according to Krasimir Tsonev and then you have it works with js parts that are executed.

 var el = str2DomElement(xmlhttp.responseText);
 document.body.innerHTML = el.innerHTML;   

Enjoy his solution:

http://krasimirtsonev.com/blog/article/Convert-HTML-string-to-DOM-element

Important notes:

  1. You need to wrap the target element with div tag
  2. You need to wrap the src string with div tag.
  3. If you write the src string directly and it includes js parts, please take attention to write the closing script tags correctly (with \ before /) as this is a string.
user3198805
  • 103
  • 1
  • 6
0

Here are 3 basic examples of what you can do with ajax & how you should do it:

Main html

js

function ajax(a,b,c){ // Url, Callback, just a placeholder
 c=new XMLHttpRequest;
 c.open('GET',a);
 c.onload=b;
 c.send()
}

function changeHTML(){
 document.getElementById('mytext1').innerHTML=this.response;
}

function executeJS(){
 (new Function(this.response))()
}

var array=[];
function loadJSON(){
 array=JSON.parse(this.response);
 updateFields();
}

function updateFields(){
 for(var a=0,b;b=array[a];++a){
  document.getElementById(b.id).textContent=b.data;
 }
}

window.onload=function(){
 ajax('getHTML.php',changeHTML);
 ajax('getJS.php',executeJS);
 ajax('getJSON.php',loadJSON);
 // even if this works you should execute ajax sequentially
}

html

<div id="mytext1"></div>
<div id="mytext2"></div>

getHTML.php

<?php
echo "<div>i'm html</div>";
?>

getJS.php

<?php
echo "var a='hello';alert(a);";
?>

getJSON.php

<?php
$arr=array(array('id'=>'mytext2','data'=>'data'));
echo json_encode($arr);//json_decode
?>

if you want to execute a javascript function use the executeJS function and pass a valid javascript string.

There is no need for EVAL!


TIP:using json you can pass a function as data but as the parsing does not like the string function at the beginning a nice trick is to convert the javascript to base64 and back into a normal string with javascript with atob(base64) and have something like this:

function updateFields(){
 for(var a=0,b;b=array[a];++a){
  if(b.func){
   (new Function(atob(b.func)))()
  }else{
   document.getElementById(b.id).textContent=b.data;
  }
 }
}

php

<?php
$arr=array(
 array('id'=>'mytext2','data'=>'data'),
 array('func'=>base64_encode("alert('jsonfunc')"))
);
echo json_encode($arr);//json_decode
?>

maybe there are some little errors ... i wrote that now. and can't check ajax atm.

if you have any questions just ask !!

cocco
  • 16,442
  • 7
  • 62
  • 77
  • Thanks for the very detailed and teaching answer. I can learn from this a lot in any case. But for the specific problem I arised, please take a look at my answer according to Krasimir Tsonev. – user3198805 Jan 28 '14 at 16:47
  • did you read the part of TIP? that explains how you could send html & javascript at the same time. – cocco Jan 28 '14 at 17:46
  • Yes. Thanks for this point. You gave several techniques that can be used for also other issues and this is good set of tools. – user3198805 Jan 28 '14 at 20:10
0

I want to give you one advice that insted use of javascript you can use jquery ajax it will be easy and latest thing for ajax.

You can use $.ajax function. You can use json easily with this function

Dhaval Rajani
  • 191
  • 1
  • 2
  • 15
0

When you make an AJAX call you contact to a server url. If your url is, as in this case, a php page, it will execute on the server and return to your AJAX call the HTML that it produces... now you can play with that HTML and manage it or publish into your current's page DOM.

-AJAX is a server call that executes server code.

-A script tag embeded on a php page is HTML that will execute the code it contains on client when parsed and executed by a browser.

So... your code isn't executing because it's never being called... the response to your AJAX call will be exactly

<p id="demo">Hi there</p>
<script>
    document.write("Yes! Hi there");    
    alert('Welcome!');
</script>

The php page executes and return that to your current page as text/html.

If you want to execute client code from your javascript you should have it on the same .js file or in another one included, but if you include it on a server page you'll need to redirect your browser to that page, if you call it with AJAX the code won't execute as the client browser won't parse it.

Bardo
  • 2,470
  • 2
  • 24
  • 42