Embedd Javascript in AJAX Response

Hi everyone…

I came across a problem few days back, it was about calling or embedding javascript result/response in AJAX response. I was working on one of the feature of PHP based site http://www.PingMyCompany.com

I found that, javascript can’t be called in AJAX response, possible reason being, AJAX response is build on server side while javascript is simply client side (I may be wrong here, OR there can be some other reason for this as well).

So what to do, what if we have to embed the output of some external JS file in AJAX response as below???

/****AJAX response START****/

/**********Some Response*******************/
/********** Some Response ******************/
/**********Response from some JS file*********/
<script src=”http://www.crunchbase.com/cbw/company/zigron.js&#8221; type=”text/javascript”>
</script>
/**********Some Response*******************/
/********** Some Response ******************/

/****AJAX response END****/

Now the response from JS file will not get embedded with AJAX response. So what I did to solve this issue is that I got the output of JS file in a PHP variable using file_get_content function as follows.

$contents = file_get_contents (“http://www.crunchbase.com/cbw/company/zigron.js&#8221;);

Alternatively you can do the same using cURL but file_get_content is really smart solution (if the JS is file is not suspicious…).

Once done, you must know the format of contents being returned by the JS file. Now you can do simple string manipulation on the contents to mangle it according to the requirements and just echo it where you want to embed it in AJAX response. I have removed document.write from the start of the string and escaped few of whitespace characters and that’s it….

****AJAX response START****

/**********Some Response*******************/
/********** Some Response ******************/
/**********Response from some JS file*********/
$content = file_get_contents (“http://www.crunchbase.com/cbw/company/zigron.js&#8221;);
$content = substr($content,16);
$content = substr($content,0, strlen ($content)-2);
$content = str_replace(“\\n”,””,$content);
$content = str_replace(“\\t”,””,$content);
$content = str_replace(‘\\”‘,””,$content);
echo $content;
/**********Some Response*******************/
/********** Some Response ******************/

/****AJAX response END****/

You can see the working example by clicking here. Click on “CrunchBase Profile” tab button which show ajax response built using remote JS file.

Feel free to discuss..

Thanks.

Keep Smiling 🙂

Posted in PHP. Tags: , , . 5 Comments »