Call and implement PHP+javascript code by using ajax


I have Mixed Code php + javascript Inside php file . I called the code inside this file by ajax .

Example of the php code

echo "<script type='text/javascript'>

The problem is that PHP code is executed, but the JavaScript code is not executed .

Is there a solution for the implementation the two codes PHP + JS using ajax request

You could output from the PHP code some data, which the javascript code then processes in certain ways. Commonly JSON is the data format that is used, so that multiple bits of data can be easily transferred as need be.

An alternative solution might be for the PHP code to send back the name of a script file which you can then add to your page.

I guess an example could be, if you’re using ajax with the GET method,


$x = $_GET['x']

echo "<script type=\\"text/javascript\\">
         document.write(\\"" . $x . "\\");


Something along those lines. You can evaluate with javascript all you want.

Now the problem comes when you want to evaluate something in javascript, and then use it by the php code, like adding in javascript and assigning to a php variable, instead of the way I can do it, which is the other way around. Not to say it’s impossible, but I’ve never tried it.

The result of the above code will write that snippet of javascript to the page that is using the ajax to call this file. So on that page, the javascript can do whatever it wants. On the page with the php, however, it is really just treated as html, not as a scripting language.