Skip to content Skip to sidebar Skip to footer

JavaScript In Php File Doesn't Work When Php File Is Called Using Ajax

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 fil

Solution 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.

Solution 2:

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


Solution 3:

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


Solution 4:

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.


Post a Comment for "JavaScript In Php File Doesn't Work When Php File Is Called Using Ajax"