Monday, April 6, 2009

Execute Javascript in PHP

Calling a PHP function from javascript is basically another way to say AJAX.
However calling a javascript function from PHP is quite a challenge.

In post-back enviroment this can be achieved easily

just use echo




This will print that tag and while the page is posting back it will get executed.

But that doesn't work in AJAX environment. Because the page is already loaded, script tags will not get executed.

Well I used this method.

When I want to call a javascript method I echo this


.





When I receive the text from AJAX partial post back






if (s.search(EXECUTESCRIPT1) >= 0 )
{
p1 = s.search(EXECUTESCRIPT1);
p2 = s.search(EXECUTESCRIPT2);
jscode = s.substr(p1 + EXECUTESCRIPT1.length, p2 - p1 - EXECUTESCRIPT2.length + 1);
eval(jscode); //execute the javavscript code
//alert("done");
}




The eval will execute the code for me after I parse it.

When I face that problem, I tried to look for something in the net but with no luck. So I thought I would write one so people can get use of it.