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.

2 comments:

  1. That's great. Indeed calling a client-side script from the server side is not a joke. I previously didn't think it was even possible and I didn't even try to find a solution but you did! Well, my projects are simpler than yours. :)

    ReplyDelete
  2. @Cody
    :)

    Well there are a bit of solutions that didn't work for me so I said lets try this anyway, so other people might find it and use it ..

    Thanks man

    ReplyDelete

Share your thoughts

Note: Only a member of this blog may post a comment.