Solved

Ajax eval creates new page with just the script

Posted on 2013-06-19
5
375 Views
Last Modified: 2013-06-22
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Búsqueda de Información</title>
<script src="../../SpryAssets/SpryValidationSelect.js" type="text/javascript"></script>
<link href="../../SpryAssets/SpryValidationSelect.css" rel="stylesheet" type="text/css" />
<script language="javascript">AC_FL_RunContent = 0;</script>
<script language="javascript"> DetectFlashVer = 0; </script>
<script src="AC_RunActiveContent.js" language="javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
var requiredMajorVersion = 10;
var requiredMinorVersion = 0;
var requiredRevision = 45;
-->
</script>

<script type="text/javascript">

function showUser(str)
	{
	if (str=="")
	  {
	  document.getElementById("Chart").innerHTML="";
	  return;
	  } 
	if (window.XMLHttpRequest)
	  {// code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	  }
	else
	  {// code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	  }
	xmlhttp.onreadystatechange=function()
	  {
	  if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
	
		 var add = document.getElementById("Chart")
    	 add.innerHTML=xmlhttp.responseText;
   		 var scripts = add.getElementsByTagName('script');
    	 for (var i = 0 ;i<scripts.length;i++) eval(scripts[i].innerHTML);
		
		}
	  }
	  
	if(str=='')
	{
	}else{
	xmlhttp.open("GET","/chart_tests/observatorio_charts.php?sel_x="+str,true);
	xmlhttp.send();	
	}
	}
	
</script>



</head>

<body>

<form action="/chart_tests/select_chart.php" method="get" style= "display:inline">


<span id="spryselect1">
<label for="sel_x">Seleccionar Eje X</label>
<select name="sel_x" id="sel_x" onchange="showUser(this.value)">

<option value="1">Año</option>
<option value="2">Municipio</option>
<option value="3">Sexo</option>
<option value="4">Edad</option>

</select>

<table>
<td>

<div id="Chart">

<?php
$sql_run = 2;

?>

<script language="JavaScript" type="text/javascript">
<!--
if (AC_FL_RunContent == 0 || DetectFlashVer == 0) {
	alert("This page requires AC_RunActiveContent.js.");
} else {
	var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	
	if(hasRightVersion) { 
		AC_FL_RunContent(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,45,2',
			'width', '400',
			'height', '350',
			'scale', 'noScale',
			'salign', 'LT',
			'bgcolor', '#777788',
			'wmode', 'opaque',
			'movie', 'charts',
			'src', 'charts',		 
			'FlashVars', 'library_path=charts_library&xml_source=/chart_tests/sample.php%3Fsql_run%3D<? echo $sql_run; ?>',
			'id', 'my_chart',
			'name', 'my_chart',
			'menu', 'true',
			'allowFullScreen', 'true',
			'allowScriptAccess','sameDomain',
			'quality', 'high',
			'align', 'middle',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'play', 'true',
			'devicefont', 'false'
			); 
	} else { 
		var alternateContent = 'This content requires the Adobe Flash Player. '
		+ '<u><a href=http://www.macromedia.com/go/getflash/>Get Flash</a></u>.';
		document.write(alternateContent); 
	}
}
// -->
</script>

</div>

</td>
</table>

<span class="selectRequiredMsg">Seleccionar</span></span>
<input name="main_menu" type=submit value="Crear Grafica" />
</form>


<script type="text/javascript">
var spryselect1 = new Spry.Widget.ValidationSelect("spryselect1");
</script>


</body>
</html>

Open in new window



This code presents an XML Chart. When I want to change the chart I am doing the Ajax call with and eval of the javascript returned (same that is within the <div> Chart but with a new number. (Got this one to finally work). Problem is that the evaluation clears the page and just brings the evaluated scrip, so only the new chart shows. Below is the returned code.

<head></head><body><embed scale="noScale" salign="LT" bgcolor="#777788" wmode="opaque" src="charts.swf" flashvars="library_path=charts_library&amp;xml_source=/chart_tests/sample.php%3Fsql_run%3D4" name="my_chart" menu="true" allowfullscreen="true" allowscriptaccess="sameDomain" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" play="true" devicefont="false" type="application/x-shockwave-flash" align="middle" height="350" width="400"> </body></html>

Open in new window


Any ideas what is wrong? I been looking for a couple of weeks trying to find a way to get a new graph without reloading the page but so far this is the only one that worked. Open to suggestions. I am new to Ajax and Java.
0
Comment
Question by:Gazu4809
  • 2
  • 2
5 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39261287
why : <head></head><body></body></html>
and not only : <embed scale="noScale" salign="LT" bgcolor="#777788" wmode="opaque" src="charts.swf" flashvars="library_path=charts_library&amp;xml_source=/chart_tests/sample.php%3Fsql_run%3D4" name="my_chart" menu="true" allowfullscreen="true" allowscriptaccess="sameDomain" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" play="true" devicefont="false" type="application/x-shockwave-flash" align="middle" height="350" width="400">

why ajax?
and not an iframe instead when you just change the src attribute
0
 
LVL 33

Expert Comment

by:Slick812
ID: 39263625
I would say that your problem is this -
var scripts = add.getElementsByTagName('script');
    	 for (var i = 0 ;i<scripts.length;i++) eval(scripts[i].innerHTML);

Open in new window


This looks like it gets ALL of your <script> sections (the TAG-name as <script>) and the trys to run the JS code in them, , as in a eval( )

This can not be right,  as you end up with a end result as -

<head></head><body><embed scale="noScale" salign="LT" bgcolor="#777788" wmode="opaque" src="charts.swf" flashvars="library_path=charts_library&amp;xml_source=/chart_tests/sample.php%3Fsql_run%3D4" name="my_chart" menu="true" allowfullscreen="true" allowscriptaccess="sameDomain" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" play="true" devicefont="false" type="application/x-shockwave-flash" align="middle" height="350" width="400"> </body></html>

which is all wrong.
In the times I have added javascript to HTML returns into a innerHTML, the browser will attempt to run that javascript with out an eval( ),
if you leave out this -
var scripts = add.getElementsByTagName('script');
    	 for (var i = 0 ;i<scripts.length;i++) eval(scripts[i].innerHTML);

Open in new window


what happens?

also you AJAX code is wrong -
function showUser(str)
	{
	if (str=="")
	  {
	  document.getElementById("Chart").innerHTML="";
	  return;
	  } 
	if (window.XMLHttpRequest)
	  {// code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	  }
	else
	  {// code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	  }

	xmlhttp.open("GET","/chart_tests/observatorio_charts.php?sel_x="+str,true);
// you MUST have the  xmlhttp.onreadystatechange AFTER the open( )
      xmlhttp.onreadystatechange=function()
	  {
	  if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
		 var add = document.getElementById("Chart")
    	 add.innerHTML=xmlhttp.responseText;
		
		}
	  }
	xmlhttp.send();	
	}

Open in new window

0
 

Author Comment

by:Gazu4809
ID: 39266344
I tried iframes momentarily but the first try did not worked (may try again) so I went back to ajax. As to the <head></head><body></body></html> that is what is returned from the call. I was expecting just the graph to be updated leaving the rest of the page intact but the code actualy clears all and just brings the noted portion. Page ends up with just the graph. As to the position in the code I had it from a posting somewhere, I'll check with this code see what happens.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39266438
Replace line 19 to 57 by the following for testing purpose :
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
	function showUser(str) {
		if(str=="") {
			jQuery("#Chart").empty();
		}
		else {
			jQuery("#Chart").load("/chart_tests/observatorio_charts.php?sel_x="+str);
		}
	}
</script>

Open in new window

0
 

Author Closing Comment

by:Gazu4809
ID: 39268059
Well I tweaked with the iframe until I got it the right syntax and its working perfectly. Thx for pushing me on the right track.

I still used ajax which loads a page with the iframe but from sites that I searched will help me do the change of the iframe locally. That will come next. At least this one is working.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

937 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

5 Experts available now in Live!

Get 1:1 Help Now