Ajax (MySQL) return value to form text area

freecrm

New Member
Messages
629
Reaction score
0
Points
0
This may be simple, it may not...

This is the process

1) Simple form

2) Dynamically generated (php) select menu with javascript onchange behaviour

3) onchange behaviour sends value currently in menu to a php page 2

4) page 2 creates mysql_result from query based on $GET value from main page 1

5) Main page 1 uses onreadystatechange to pull result from page 2 and display.


The current methodology uses the getElementById() to send result to a pre-specified div with that id.

What I want to do is to place that value into a form <textarea>

I can't place the whole <div id=" in a default value, so how can I achieve this?

Please understand that while my php skills are OK, my JS skills are not :)

Page 1 ajax code

Code:
var xmlhttp;
function GetInfo(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Browser does not support HTTP Request");
  return;
  }
var url="page2.php";
url=url+"?link="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("ajax").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}
</script>

Stripped down Page 1 html

Code:
<form id="form1" name="form1" method="post" action="">
  <label for="Example">Example</label>
    <select name="Example" id="Example" onchange="GetInfo(this.value)">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    </select>
    <label for="FillIn">Text Area</label>
    <textarea name="FillIn" id="FillIn" cols="45" rows="5"></textarea>
</form>
 
<div id="ajax">Default Primary Deck Spec will appear here.</div>

Any ideas?
 

descalzo

Grim Squeaker
Community Support
Messages
9,375
Reaction score
327
Points
83
If all you are asking is how to put the return text into the text area:

Code:
function stateChanged()
{
if (xmlhttp.readyState==4)
{


document.getElementById("FillIn").value=xmlhttp.responseText;
}
}
 
Last edited:

freecrm

New Member
Messages
629
Reaction score
0
Points
0
Duh - that WAS simple - thanks

To complicate matters slightly, I now need to append several fields called by the onchange event.

I thought this was going to be simple purely by adding another action to the onchange command

i.e.

Code:
onchange="GetInfo(this.value); GetDetail(this.value);"

I would then copy/paste the JS, altering the command name to GetDetail and changing the output location

document.getElementById("formfield2").innerHTML=xmlhttp.responseText;

This additional JS would then call a different php page obtaining separate data.


....but this doesn't work!
 
Last edited:

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
Can you post your code? Maybe a typo?

@Descalzo: BTW, the way I learned it was
Code:
   request.onreadystatechange = function() {
     if (request.readyState == 4) {
        if (request.status == 200) {

Is the "if(request.status==200)" unnecessary?
 
Last edited:

descalzo

Grim Squeaker
Community Support
Messages
9,375
Reaction score
327
Points
83
@Descalzo: BTW, the way I learned it was
Code:
   request.onreadystatechange = function() {
     if (request.readyState == 4) {
        if (request.status == 200) {

Is the "if(request.status==200)" unnecessary?

Depends how you handle 404 (file not found) or 500 (Server Error) type responses. If you are expecting simple text or javascript and try to parse an error page, you get garbage. If you just display the response, it can be ugly, but help in debugging. In the final product, yes you should test the response status and handle each appropriately (even if it is to ignore those other than 200)

I have a habit of just fixing the problem that someone posts rather than rewriting everything to "production standards".
 
Last edited:

freecrm

New Member
Messages
629
Reaction score
0
Points
0
Can you post your code? Maybe a typo?

OK here goes..

JS..

Code:
<script type="text/javascript">
		var xmlhttp;
		
		function GetBasicInfo(str)
		{
		xmlhttp=GetXmlHttpObject();
		if (xmlhttp==null)
		  {
		  alert ("Browser does not support HTTP Request");
		  return;
		  }
		var url="/spec/ajax/ajax_basic_info.php";
		url=url+"?link="+str;
		url=url+"&sid="+Math.random();
		xmlhttp.onreadystatechange=stateChanged;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
		}
		
		function stateChanged()
		{
		if (xmlhttp.readyState==4)
		{
		document.getElementById("BasicInfo").innerHTML=xmlhttp.responseText;
		}
		}
		
		function GetXmlHttpObject()
		{
		if (window.XMLHttpRequest)
		  {
		  // code for IE7+, Firefox, Chrome, Opera, Safari
		  return new XMLHttpRequest();
		  }
		if (window.ActiveXObject)
		  {
		  // code for IE6, IE5
		  return new ActiveXObject("Microsoft.XMLHTTP");
		  }
		return null;
		}
    </script>
<script type="text/javascript">
		var xmlhttp;
		
		function GetDetailedInfo(str)
		{
		xmlhttp=GetXmlHttpObject();
		if (xmlhttp==null)
		  {
		  alert ("Browser does not support HTTP Request");
		  return;
		  }
		var url="/spec/ajax/ajax_detailed_info.php";
		url=url+"?link="+str;
		url=url+"&sid="+Math.random();
		xmlhttp.onreadystatechange=stateChanged;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
		}
		
		function stateChanged()
		{
		if (xmlhttp.readyState==4)
		{
		document.getElementById("DetailedInfo").innerHTML=xmlhttp.responseText;
		}
		}
		
		function GetXmlHttpObject()
		{
		if (window.XMLHttpRequest)
		  {
		  // code for IE7+, Firefox, Chrome, Opera, Safari
		  return new XMLHttpRequest();
		  }
		if (window.ActiveXObject)
		  {
		  // code for IE6, IE5
		  return new ActiveXObject("Microsoft.XMLHTTP");
		  }
		return null;
		}
    </script>

html form and div's

Code:
<select name="type" id="type" style="" onchange="GetBasicInfo(this.value); GetDetailedInfo(this.value)" >


...blah de blah..

<div id="BasicInfo">Basic Info goes here</div>

<div id="DetailedInfo">Detailed Info Ggoes here</div>

php (one page example for ajax_basic_info.php)

PHP:
require_once('../../Connections/dbcrmauto.php');
mysql_select_db("DBCRM1") or die('Could not select DB: ' . mysql_error());

$ajaxlink=$_GET["link"];


$ajaxsql="SELECT * FROM Info WHERE basic_info = '".$ajaxlink."'";

$ajaxresult = mysql_query($ajaxsql);

while($ajaxrow = mysql_fetch_array($ajaxresult))
  {
  echo $ajaxrow['basic_info'];
  }
;

mysql_free_result($ajaxresult);

Any ideas?
 
Last edited:

descalzo

Grim Squeaker
Community Support
Messages
9,375
Reaction score
327
Points
83
1. In what way doesn't it work?

2. One problem I see immediately is that you are clobbering the first request with the second.
GetBasicInfo called, sets xmlhttp and returns before xmlhttp returns
GetDetailedInfo called, resets xmlhttp, losing the first call.
Try using different names for the two request objects.
 

freecrm

New Member
Messages
629
Reaction score
0
Points
0
1. In what way doesn't it work?

On statechange, neither script appears to function, having no effect on either id basic info or detailed info.

2. One problem I see immediately is that you are clobbering the first request with the second.
GetBasicInfo called, sets xmlhttp and returns before xmlhttp returns
GetDetailedInfo called, resets xmlhttp, losing the first call.
Try using different names for the two request objects.

OK... that sort of makes sense.. bearing in mind I read JS like its in martian! :)

I tried renaming the "xmlhttp" variable to "xmlhttp1" and "xmlhttp2" for each case, but this had no effect either.

Maybe I'm looking at this the wrong way..

All I need to do is auto-fill a number of empty fields with data that comes back from a single Table, based on the state chage of 1 drop-down menu.

For instance, if the user chooses option 2 from the menu, form fields 3,5,7 and 9 will auto fill from the table "eg contents" contents.3, contents.5, contents.7, contents.9 etc.

Beofre I tried this method, an array seemed more likely, but I can't figure the JS to capture this and, more importantly, place it in in the right places.
 

descalzo

Grim Squeaker
Community Support
Messages
9,375
Reaction score
327
Points
83
Make one request.
Have the php return a string with the results for the columns separated by a delimiter, ie a comma or colon
array_of_results = result.split( ':' ) ; will split the result into an array so you can put each value where you want.
XML would be another, more complicated choice of return.
JSON would be a third.
 

essellar

Community Advocate
Community Support
Messages
3,295
Reaction score
227
Points
63
I tried renaming the "xmlhttp" variable to "xmlhttp1" and "xmlhttp2" for each case, but this had no effect either.

The problem very likely lies in your GetXmlHttpRequestObject() function -- it is assigning all requests to a single XmlHTTPRequest instance, so you really aren't getting asynchronous behaviour. There is no reason (other than to reduce request traffic) to fold all of your page requests into one as suggested elsewhere. You should be able to make the request an array in the function and increment the index on each call, returning only that member of the array for each call to GetXmlHttpRequestObject().
 

freecrm

New Member
Messages
629
Reaction score
0
Points
0
Thanks for the pointers here. Array system it is then!

I have amended the php to output an array-type string

PHP:
echo $ajaxrow['basic_info'].":".$ajaxrow['detailed_info'];

and then changed the js to the following

Code:
function stateChanged()
		{
		if (xmlhttp.readyState==4)
		{
		var result_array = xmlhttp.responseText.split(":"); 
		document.getElementById("BasicInfo").innerHTML=result_array[0];
		document.getElementById("DetailedInfo").innerHTML=result_array[1];
		}
		}

After testing, the array is returning results correctly, but only the first getElementById is executing.

I'm assuming this is because the...

Code:
onchange="GetDeckInfo(this.value)"

... only returns one value?

Or am I missing something simple here?
 

Jake

Developer
Contributors
Messages
4,057
Reaction score
5
Points
0
Here's an option you might find helpfull.

As much as I hate using pre-existing code, and believe me, I do. I have to admit that writing your own scratch AJAX code is almost too complex a task to do for a site that implements a lot of AJAX. Thanks to people who have way too much free time on their hands we get special things like jQuery.

Heres the site: http://jquery.com/
Here is the documentation on ajax post: http://api.jquery.com/jQuery.post/

1. First off, it's easy, just put the javascript file for jquery (probably the minimal one) into your sites styles or javascript folder and make sure you link it:

Code:
<script type="text/javascript" src="location/jquery-1.4.2.min.js"></script>

2. You can use it to open POST requests (AJAX) and send arrays and data:
The javascript code (in a javascript file or inside <style type="text/javascript"></style>):
Code:
$(document).ready(function()
{
	// When you click on the object with id "button" run the ajax
	$('#button').click(function()
	{
		// Ajax request, we send a $_POST[] called choices to the php which is actually going to be an array
		$.post("test.php", { 'choices[]': ["Jon", "Susan"] }, function(data)
		{
     			// This inside part is what is returned after the AJAX is fully executed and in state 4
    			$('#id_of_content_box').html(data);
		});
	});
});
The above code will send the array to the php file (test.php) and return the "data" variable as you can see in the function(data) will be putting that data into a div or element with the id id_of_content_box.

3. The above code will sent a request for test.php... inside test.php we can do the following:
This is just a basic example of php code to show you how it works.

Code:
$array = $_POST['choices']; 
echo $array[0].":".$array[1];

4. Will return something like:

Code:
Jon:Susan

That will be inside the element with the id of "id_of_content_box"

Some basics:
1. $('#idhere').val() = the value of an form field, can be changed with .val("stuff here")

Here's an example of an AJAX post request, getting the variables from a form
The html form:
Code:
<input name="name" type="text" id="name" /><br />
<input name="phone" type="text" id="phone" /><br />
<input name="button" type="button" value="Send" id="button" />
The javascript code (in a javascript file or inside <style type="text/javascript"></style>):
Code:
// This code works when the document has finished loading
$(document).ready(function()
{
	// When you click on the button to "submit" the form
	$('#button').click(function()
	{
		// This send request will send $_POST[]'s for name and phone ($_POST['name'] and $_POST['phone'])
		$.post("test.php", { name:$('#name').val(), phone:$('#phone').val() }, function(data)
		{
     			// This inside part is what is returned after the AJAX is fully executed and in state 4
    			$('#id_of_content_box').html(data);
		});
	});
});

2. $('xxxx') = you can replace the xxx with '.classhere' or '#idhere' to select things that are ids or classes and even the name attribute (not XML strict 'valid').
3. All basic form events have a .click(), .change(), .keyup(), etc.
4. You can do cool things like .fadeOut(time) and .fadeIn(time) for data that is hidden.

Why would I tell you to use this if I myself am against pre-coded work?
Now think for a minute. Building web pages is about learning, and functionality. When you are finished learning how AJAX works you need to make it functional. We all know about the XMLHTTPRequest objects but doing all the background setup code by hand is very tedious and hard to make work correctly. I have recently migrated over to using jQuery for ALL my javascript needs because it is simple and hardly ads any size onto my files. The whole point of jQuery is to be fast, easy, and you know what, I personally think jQuery is quite fun once you get to know it.

Now if you do decide to use it, go to their website for all documentation needs. They have great documentation on the current functions and have live examples in most of them to show how they work. It's actually quite simple when you get to understanding it.

Anyway, hope this helps you and you get your web page working.
 
Last edited:

freecrm

New Member
Messages
629
Reaction score
0
Points
0
Thanks for the heads up on jquery, but in order for me to understand JS and ajax better, I really need to understadn this.

Fortunately, after a lot of reading up, I have found the solution.

Code:
var result_array = xmlhttp.responseText.split("[|]");
document.getElementById("2ndDeckDesc").innerHTML=result_array[0];
document.getElementById("DeckT").value=result_array[1];

The 2nd array value was returning an integer value so I just changed the "innerHTML" for "value" and it worked a treat.

Thanks for all the help.
 

Jake

Developer
Contributors
Messages
4,057
Reaction score
5
Points
0
You could also just concatenate the integer value onto a string before you put it into the innerHTML, but doesn't make a difference unless you're going to be outputting more with the value.

(Yeah, don't worry, I used to be just like you :p)
 
Top