Link to home
Start Free TrialLog in
Avatar of mrh14852
mrh14852

asked on

AJAX, Javascript, PHP, Mysql, Forms, upates without page refresh...need help getting started

Here is my scenario.  I realize I need to use AJAX to accomplish what I am trying to do however everything I have read through so far has not lead me to the answer.

I am using a javascript charting application that I build using PHP functions that I wrote.  I pass a few variables into the function and it builds the javascript I need including the data the function gets from a query and puts it into the HEAD of my page.

For example a function could be like this   get_chart_1($catA, $catB, $div).
So if I was going to use this to build chats on a page my html page would look like this.


<head>
<?php
get_chart_1("ABC", "123", "chart1");
get_chart_2("DEF", "456", "chart2");
?>
</head>

this creates something like the following...

<head>
<script type="text/javascript">
javascript code for chart 1
~~
</script>

<script type="text/javascript">
javascript code for chart 2
~~
</script>
</head>

Please note only the chart JS is generated by the php functions, the rest of the html page is hand written.

<body>
<div class="wrapper">
  <div class="header"></div>
  <div id="chart1"></div>
</div>

<div class="wrapper">
  <div class="header"></div>
  <div id="chart1"></div>
</div>

This all works great and I am quite pleased with the results.

The next step I wanted to add was making the charts more interactive but doing so by avoiding a complete page refresh, so someone can just update a chart in a single div.  I want to do this by adding a form in the header of each div with a couple of drop-downs and upon submit would pass the selections through my php functions to update the chart in just that div.

So it would be something like this...

<body>
<div class="wrapper">
  <div class="header">
    <form enctype="application/x-www-form-urlencoded" name="form1" id="form1">
      <input type="hidden" name="div" value="chart1" />
      <select name="catA"><option value="ABC">ABC</option><option value="DEF">DEF</option></select>
      <select name="catB"><option value="123">123</option><option value="456">456</option></select>
      <input type="submit" name="submit" value="Submit" />
    </form>
  </div>
  <div id="chart1"></div>
</div>

<div class="wrapper">
  <div class="header">
    <form enctype="application/x-www-form-urlencoded" name="form2" id="form2">
      <input type="hidden" name="div" value="chart2" />
      <select name="catA"><option value="ABC">ABC</option><option value="DEF">DEF</option></select>
      <select name="catB"><option value="123">123</option><option value="456">456</option></select>
      <input type="submit" name="submit" value="Submit" />
    </form>
  </div>
  <div id="chart1"></div>
</div>


So after submit from the div it passes the selected categories back through the functions to rebuild the chart in the div with the new values.

Your help is most appreciated.
Avatar of Proculopsis
Proculopsis


Manipulating the dom is a nicer solution but you can do something like this by jamming some alternate html into the div.

<html>
<head>
<title>http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q__26630379.html</title>

<script>

function eventOnChangeCategory( select )
{
  var render = 
  [
    null,
    '<img src="https://www.opendns.com/dashboard/img/placeholder_md.gif" />',
    '<img src="https://www.opendns.com/dashboard/img/placeholder_sm.gif" />'
  ];
  if ( select.selectedIndex != 0 )
  {
    document.getElementById("chart1").innerHTML = render[select.selectedIndex];
  }
}
</script>

<style>
#chart1 { width: 145px; height: 100px; border: 1px solid red; }
</style>

</head>

<body>

<select onchange="eventOnChangeCategory(this);">
  <option>Select...</option>
  <option>CatA</option>
  <option>CatB</option>
</select>

<div id="chart1">
<div>

</body>

</html>

Open in new window

Your problem here, as I think... is that your server php functions return to your page js code that builds graphics on page load.

So if you want to allow users to generate new graphics without reloading page you're in trouble, because your graphics generates on page load!

The usual way to do this type of things is that server code return html code to your page that's inserted on container divs on execution time. This way, you can make an AJAX call to your server functions and inject the responsed HTML into a container, refreshing this page part without a full reload.

On your scenario will be very difficult to do something like this, as your server code will modify page's javascript, and it won't reexecute without a full reload.

From my point of view you have two options:

1) Change your code to make your server functions return graphics HTML and make AJAX calls to those functions when you want to generate a new graphic.

2) Change your server functions to return all the js to build all possible graphics, and hide/show those graphics depending on dropdown selected value.
Avatar of SAMIR BHOGAYTA
Hello,

Use the Update Panel of Ajax Extension. Then try again.
Avatar of mrh14852

ASKER

Thanks to everyone so far
@Proculopsis
I think the problem with that method is the sheer amount of choices the user will have to change the criteria of the chart and I am not rendering graphics, I am rendering javascript that creates an interactive charht (there are controls in the chart as well)..  This was why I was trying to see if there was a way to just pass the variables from the form back into my php functions.

@Bardobrave
Yes this is exactly what I am encountering.  I can move the PHP functions into the <body> but I guess it's still the same problem, that they are being built on page load...for option 2...it would be a massive amount of queries all at once...but...may be my only option...how would i accompish this?
Or....how about moving the code for each individual div into the <body> and use javascript to build the actual php functions based on the selection criteria itself?  or would that still require a page load...
ASKER CERTIFIED SOLUTION
Avatar of Bardobrave
Bardobrave
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The functions create the actual JS code.

For example:

my PHP function is like this...
get_chart_1($catA, $catB, $div)

so on initial page load I may have something like this either in the head or in a div.

<?php %chart1 = get_chart_1("category a", "category 1", "mychartdiv"); echo $chart1; ?>

will return something like the following...
<script type="text/javascript">
     var chart;
     $(document).ready(function(){
     chart: { renderTo: mychartdiv, defaultSeriesType: 'line', borderRadius: 0, height: 568 },
     etc...
     etc...
     etc...
</script>


I have been trying to play around with this and I have been able to create a form that makes a request to a php script which all it is doing is echoing the javascript back...but I am stuck there.

If I look at it in Firefox Firebug and look at the get and response I can see the code is being echoed back properly but it's not showing up on my page.

I have tested my AJAX script by just echoing a single word back and it works fine...is there something I need to do to get it to recognize the javascript that is echoed back?
Okay so I figured out why the chart doesn't show up and that's because the javascript is not present during the page load.

I need to somehow evaluate the scripts that are returned to the DOM and run them...

Here is my ajax code:

<script language="javascript" type="text/javascript">
function ajaxFunction(){
	var ajaxRequest;
	try {
		ajaxRequest = new XMLHttpRequest();
	}
	catch (e) {
		try {
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {
				alert("Upgrade Browser");
				return false;
			}
		}
	}
ajaxRequest.onreadystatechange = function() {
	if(ajaxRequest.readyState == 4) {
		var ajaxDisplay = document.getElementById('chart');
		ajaxDisplay.innerHTML = ajaxRequest.responseText;
	}
}
var aaa = document.getElementById('aaa').value;
var bbb = document.getElementById('bbb').value;
var ccc = document.getElementById('ccc').value;
var queryString = "?aaa=" + aaa + "&bbb=" + bbb + "&ccc=" + ccc;
ajaxRequest.open("GET", "testq.php" + queryString, true);
ajaxRequest.send(null);
}
</script>

Open in new window

Well...I was able to resolve that issue by finding some eval code and changing my ajax code to this.

<script language="javascript" type="text/javascript">
function getchart()
{
	var aaa = document.getElementById('aaa').value;
	var bbb = document.getElementById('bbb').value;
	var ccc = document.getElementById('ccc').value;
	var queryString = "?aaa=" + aaa + "&bbb=" + bbb + "&ccc=" + ccc;
	http.open("GET", "testq.php" + queryString, true);
	http.onreadystatechange = handleHttpResponseUser;
	http.send(null);
		
}
function handleHttpResponseUser() 
{
	if (http.readyState == 4) 
	{
		resultsuser = http.responseText;
		if(resultsuser == "") resultsuser = "Blank";
		document.getElementById('chart').innerHTML = resultsuser;
		
		scriptTag='(<script.*?>)((\n|\r|.)*?)(<\/script>)';
		if (scripts=resultsuser.match(scriptTag)) {
		 	scripts[2]=scripts[2].replace(/\\/g,"");
		 	eval(scripts[2]);
		}
		
	}
}
function getHTTPObjectUser() 
{
	var xmlhttp;
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 
	{
		try {xmlhttp = new XMLHttpRequest();} catch (e) {xmlhttp = false;}
	}
	
	return xmlhttp;
}
var http = getHTTPObjectUser();
</script>

Open in new window

I figured out what I needed to do and everything is working.  Bardobrave I guess you get the points for steering me in the right direction...thanks.
I'm glad you've been finally able to solve it.
I figured it out for myself...no coding provided was able to hekp me...however I was steered in the right direction.  thanks