Solved

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

Posted on 2010-11-21
13
464 Views
Last Modified: 2012-05-10
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.
0
Comment
Question by:mrh14852
13 Comments
 
LVL 20

Expert Comment

by:Proculopsis
ID: 34185960

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

0
 
LVL 19

Expert Comment

by:Bardobrave
ID: 34186071
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.
0
 
LVL 11

Expert Comment

by:SAMIR BHOGAYTA
ID: 34186270
Hello,

Use the Update Panel of Ajax Extension. Then try again.
0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 8

Author Comment

by:mrh14852
ID: 34189631
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?
0
 
LVL 8

Author Comment

by:mrh14852
ID: 34189698
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...
0
 
LVL 19

Accepted Solution

by:
Bardobrave earned 500 total points
ID: 34190299
I'm not sure how your js are defined and your graphics builded, but if you can generate your graphics html code and it's control's js through server code you can push it from server to client side with an AJAX call without full page reload.

Keep in mind that what an AJAX call does is execute a server side function without redirecting execution out of current page, and when server function returns, the data returned can be injected to the page to produce the reload of one part of the page.

You'll probably have to make a twist to your server side functions, but keeping this in mind it shouln't be difficult to acomplish.
0
 
LVL 8

Author Comment

by:mrh14852
ID: 34190411
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>


0
 
LVL 8

Author Comment

by:mrh14852
ID: 34194049
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?
0
 
LVL 8

Author Comment

by:mrh14852
ID: 34194094
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

0
 
LVL 8

Author Comment

by:mrh14852
ID: 34194139
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

0
 
LVL 8

Author Comment

by:mrh14852
ID: 34194232
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.
0
 
LVL 19

Expert Comment

by:Bardobrave
ID: 34194405
I'm glad you've been finally able to solve it.
0
 
LVL 8

Author Closing Comment

by:mrh14852
ID: 34233128
I figured it out for myself...no coding provided was able to hekp me...however I was steered in the right direction.  thanks
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

831 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