Evaluate scripts while working on AJAX Requests

Advertisement

Introduction

Recently, one of my reader came up with a query like “Why JavaScript is not running after loading a page through AJAX, but if we run the respective page alone without any AJAX – JavaScript is working fine”, Yeah, I do faced this sort of problem while I am loading respective pages through AJAX. To know more about how to load an external page through AJAX, here is the nice post of the same “Snippet Code for Simple Ajax Tabs with cool CSS Styles“.

Solution

For this to resolve, we need to parse the code which we are loading through AJAX, that is once httprequest status is 200 (I mean ’success’), while sending the respective rendered data to a place holder or any div (in the form of ‘innerHTML‘) you need to parse/evaluate the content accordingly. I mean need to check whether any JavaScript code/ Script Tag is present in the respective HTML content or not, for this actually we need to use “eval” to evaluating the script accordingly. Below is the generic function we need to call when respective content is loading through AJAX. Just go through the code you will let you know everything.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function parseScript(_source) {
		var source = _source;
		var scripts = new Array();
 
		// Strip out tags
		while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
			var s = source.indexOf("<script");
			var s_e = source.indexOf(">", s);
			var e = source.indexOf("</script", s);
			var e_e = source.indexOf(">", e);
 
			// Add to scripts array
			scripts.push(source.substring(s_e+1, e));
			// Strip from source
			source = source.substring(0, s) + source.substring(e_e+1);
		}
 
		// Loop through every script collected and eval it
		for(var i=0; i<scripts.length; i++) {
			try {
				eval(scripts[i]);
			}
			catch(ex) {
				// do what you want here when a script fails
			}
		}
		// Return the cleaned source
		return source;
}

Call the above function like below (that is once the httprequest.status is ’success’)

1
2
3
4
5
6
7
8
9
10
11
function responsefromServer(divElementId, pageErrorMessage) {
   var output = '';
   if(req.readyState == 4) {
      if(req.status == 200) {
         output = req.responseText;
         document.getElementById(divElementId).innerHTML = parseScript(output);
         } else {
         document.getElementById(divElementId).innerHTML = pageErrorMessage+"\n"+output;
         }
      }
  }

Below is the full code

For reference, goto the article – Snippet Code for Simple Ajax Tabs with cool CSS Styles, just download the respective file and after unzipping, click on JS folder and open ‘ajax.js‘ in your respective editor and compare, you will get an idea on how we can overcome our problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var req;
function callPage(pageUrl, divElementId, loadinglMessage, pageErrorMessage) {
     document.getElementById(divElementId).innerHTML = loadinglMessage;
     try {
     req = new XMLHttpRequest(); /* e.g. Firefox */
     } catch(e) {
       try {
       req = new ActiveXObject("Msxml2.XMLHTTP");  /* some versions IE */
       } catch (e) {
         try {
         req = new ActiveXObject("Microsoft.XMLHTTP");  /* some versions IE */
         } catch (E) {
          req = false;
         } 
       } 
     }
     req.onreadystatechange = function() {responsefromServer(divElementId, pageErrorMessage);};
     req.open("GET",pageUrl,true);
     req.send(null);
  }
 
function responsefromServer(divElementId, pageErrorMessage) {
   var output = '';
   if(req.readyState == 4) {
      if(req.status == 200) {
         output = req.responseText;
         document.getElementById(divElementId).innerHTML = parseScript(output);
         } else {
         document.getElementById(divElementId).innerHTML = pageErrorMessage+"\n"+output;
         }
      }
  }
 
function parseScript(_source) {
		var source = _source;
		var scripts = new Array();
 
		// Strip out tags
		while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
			var s = source.indexOf("<script");
			var s_e = source.indexOf(">", s);
			var e = source.indexOf("</script", s);
			var e_e = source.indexOf(">", e);
 
			// Add to scripts array
			scripts.push(source.substring(s_e+1, e));
			// Strip from source
			source = source.substring(0, s) + source.substring(e_e+1);
		}
 
		// Loop through every script collected and eval it
		for(var i=0; i<scripts.length; i++) {
			try {
				eval(scripts[i]);
			}
			catch(ex) {
				// do what you want here when a script fails
			}
		}
		// Return the cleaned source
		return source;
}

Above code will help you a lot while developing AJAX related Web Applications…

Related Entries...

World News:

2 Responses

05.20.09

Hello,
Its me again , can you please to find some tips about “recent comment” but using Jquery ?I am looking for it for days but I still not see any.
I am very thank you if you publish 1 tip about it .
Have a gooday my friend
Zen

[...] to eval() the XMLHttpRequest data being sent. But thanks to developersnippets.com they wrote a very helpful article that fixes the issues I was [...]

Leave Your Response

* Name, Email, Comment are Required

Online Sponsors

Start Foreign Exchange Trading today with the Forex Affiliate Program and also you can have access Online Forex News to know what happens every single moment.


Forex Floor