Solved

how to load ajax returned value inside a text area

Posted on 2009-05-13
11
659 Views
Last Modified: 2013-12-12
Hi,

i want to load database table value to a rich text editor. i want to load values inside textarea.

when i run the code individually using a textarea and load the values using ajax its working fine but when i integrate with the editor its not working

am using the editor from the following link

http://www.htmlarea.com/directory/Detailed/185.html

this code works fine

 
  <script type="text/javascript">

function getXMLHTTP() { //fuction to return the xml http object
            var xmlhttp=false;      
            try{
                  xmlhttp=new XMLHttpRequest();
            }
            catch(e)      {            
                  try{                  
                        xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  catch(e){
                        try{
                        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                        }
                        catch(e1){
                              xmlhttp=false;
                        }
                  }
            }
                   
            return xmlhttp;
    }
      
      function getState(typeId) {            
            
            var strURL="findtype1.php?type="+typeId;
            var req = getXMLHTTP();
            
            if (req) {
                  
                  req.onreadystatechange = function() {
                        if (req.readyState == 4) {
                              // only if "OK"
                              if (req.status == 200) {                                    
                                    document.getElementById('TextArea1').value=req.responseText;                                    
                              } else {
                                    alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                              }
                        }                        
                  }                  
                  req.open("GET", strURL, true);
                  req.send(null);
            }            
      }
      
</script>  

 
      
  <form id="editors_here" action="simple_example_landing.php" method="post">

    <textarea id="TextArea1" name="TextArea1" rows="10" cols="80" style="width:100%">
       </textarea>

      <br>

      
      <input type="button" value="submit" onClick="javascript:submitHandler('editors_here');">
   
   Type: <select name="type" onChange="getState(this.value)">
      <option value="">Select type</option>
      <option value="1">Local Clinic</option>
      <option value="2">Company</option>
        </select>
   
   
   
   
   
  </form>
 
  <div id="statediv">
</div>

<br>
<br>


<br>
</body>
</html>


But when i use this with editor it does not work pls helpppp

the concept does not work here with this code
 
 
 
 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>
 

<?php 
 

/**

* Simple Example

*

* This file demonstrates how to turn a simple Text Area into an AreaEdit component

* and how to do a javascript submit.

*

* This file was originally written by James Sleeman of Gogo Code and comes from the

* Xinha project.

*/
 

?>
 

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Simple Example of AreaEdit</title>

  <link rel="stylesheet" href="examples.css" />

  

  

  <script type="text/javascript">
 

function getXMLHTTP() { //fuction to return the xml http object

		var xmlhttp=false;	

		try{

			xmlhttp=new XMLHttpRequest();

		}

		catch(e)	{		

			try{			

				xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");

			}

			catch(e){

				try{

				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

				}

				catch(e1){

					xmlhttp=false;

				}

			}

		}

		 	

		return xmlhttp;

    }

	

	function getState(typeId) {		

		

		var strURL="findtype1.php?type="+typeId;

		var req = getXMLHTTP();

		

		if (req) {

			

			req.onreadystatechange = function() {

				if (req.readyState == 4) {

					// only if "OK"

					if (req.status == 200) {						

						document.getElementById('TextArea1').value=req.responseText;						

					} else {

						alert("There was a problem while using XMLHTTP:\n" + req.statusText);

					}

				}				

			}			

			req.open("GET", strURL, true);

			req.send(null);

		}		

	}

	

</script> 
 

  

  

  

  

  

  

  

  

  

  
 

  <script type="text/javascript">
 

	var _editor_url;

	var _editor_lang;
 

    // You must set _editor_url to the URL (including trailing slash) where

    // where AreaEdit is installed, it's highly recommended to use an absolute URL

    //  eg: _editor_url = "/path/to/areaedit/";

    // You may try a relative URL if you wish]

    //  eg: _editor_url = "../";
 

    // for this example we're using a little regular expression to find the absolute path.

	 // so that this demo will work "out of the box".

	 // 

	 // However, this means if you change the name of this page or the use this code in 

	 // your own page you will need to set _editor_url below. 

	 //

	 // Please note that the value of _editor_url must contain a trailing slash.
 

    _editor_url  = document.location.href.replace(/examples\/simple_example\.php.*/, '')
 

    _editor_lang = "en";      // And the language we need to use in the editor.
 

  </script>
 

  <!--  load in debug trace message class -->
 

  <script type="text/javascript" src="../ddt/ddt.js"></script>
 

  <script type="text/javascript">
 

  // create a global debug object to track everything that happens

  // during startup.
 

  var startupDDT = new DDT( "startup" );
 

  // uncomment the following if you would like to trace out the 

  // startup functions. This only works in the debugging version

  // of AreaEdit, not the runtime.

  //

  // startupDDT._ddtOn();
 

  </script>

  

  <!-- Load up the actual editor core -->

  <script type="text/javascript" src="../htmlarea.js"></script>
 

  <script type="text/javascript">
 

   var areaedit_editors = null;

   var areaedit_init    = null;

   var areaedit_config  = null;

   var areaedit_plugins = null;
 

	startupDDT._ddt( "simple_example.html", "71", "Setting up areaedit_init()" );
 

	// --------------------------------------------------------------------------------
 

	/**

	* sample initialization function 

	*

	* this is called from the body onload handler below. It sets up the configurations

	* and builds the editor.

	*/
 

	areaedit_init = function()

		{
 

		// This is a workaround for a bug in MSIE that sometimes produces

		// "Operation Aborted" errors. The error comes from the fact that

		// MSIE will /sometimes/ call the onload handler before the DOM

		// heirarchy is completely built. 

		//

		// So we do not run this function until the page has completely 

		// loaded if we are MSIE.
 

		if ( HTMLArea.is_ie && document.readyState != "complete" )

			{

			setTimeout( function() { areaedit_init()}, 50 );

			return false;

			}
 

		startupDDT._ddt( "simple_example.html", "76", "areaedit_init called from window.onload handler for simple_example.php" );
 

		// Initialize the HTMLArea class. (Used to be at the bottom of htmlarea.js)
 

		HTMLArea.init();
 

      /** STEP 1 ***************************************************************

       * First, what are the plugins you will be using in the editors on this

       * page.  List all the plugins you will need, even if not all the editors

       * will use all the plugins.

       ************************************************************************/
 

		// a minmal list of plugins.
 

      var areaedit_plugins_minimal = 

      [

       'ContextMenu',

       'Linker',

		 'ImageManager'

      ];
 

      // This loads the plugins. We're using a very minimal list

		// here.

		//

		// loadPlugins causes the plugin .js files (in this case content-menu.js,

		// linker.js and image-manager.js) in the "background". The second parameter

		// here is a callback that gets invoked while we're waiting for things to load,

		// which in this case just causes us to loop back to here. Once everything 

		// is loaded loadPlugins() returns true and we can continue on.
 

	   startupDDT._ddt( "simple_example.html", "92", "calling HTMLArea.loadplugins()" );
 

      if ( !HTMLArea.loadPlugins( areaedit_plugins_minimal, areaedit_init)) 

			{

			return;

			}
 

      /** STEP 2 ***************************************************************

       * Now, what are the names of the textareas you will be turning into

       * editors? For this example we're only loading 1 editor.

       ************************************************************************/
 

      areaedit_editors = 

      [

        'TextArea1'

      ];
 

      /** STEP 3 ***************************************************************

       * We create a default configuration to be used by all the editors.

       * If you wish to configure some of the editors differently this will be

       * done in step 4.

       *

       * If you want to modify the default config you might do something like this.

       *

       *   areaedit_config = new HTMLArea.Config();

       *   areaedit_config.width  = 640;

       *   areaedit_config.height = 420;

       *

       *************************************************************************/
 

  	    startupDDT._ddt( "simple_example.html", "119", "calling HTMLArea.Config()" );
 

       areaedit_config = new HTMLArea.Config();
 

      /** STEP 3 ***************************************************************

       * We first create editors for the textareas.

       *

       * You can do this in two ways, either

       *

       *   areaedit_editors   = HTMLArea.makeEditors(areaedit_editors, areaedit_config, areaedit_plugins);

       *

       * if you want all the editor objects to use the same set of plugins, OR;

       *

       *   areaedit_editors = HTMLArea.makeEditors(areaedit_editors, areaedit_config);

       *   areaedit_editors['myTextArea'].registerPlugins(['Stylist','FullScreen']);

       *   areaedit_editors['anotherOne'].registerPlugins(['CSS','SuperClean']);

       *

       * if you want to use a different set of plugins for one or more of the

       * editors.

       ************************************************************************/
 

      startupDDT._ddt( "simple_example.html", "140", "calling HTMLArea.makeEditors()" );
 

      areaedit_editors   = HTMLArea.makeEditors(areaedit_editors, areaedit_config, areaedit_plugins_minimal);
 

      /** STEP 4 ***************************************************************

       * If you want to change the configuration variables of any of the

       * editors,  this is the place to do that, for example you might want to

       * change the width and height of one of the editors, like this...

       *

       *   areaedit_editors.myTextArea.config.width  = 640;

       *   areaedit_editors.myTextArea.config.height = 480;

       *

       ************************************************************************/
 

       areaedit_editors.TextArea1.config.width  = 700;

       areaedit_editors.TextArea1.config.height = 350;
 

      /** STEP 5 ***************************************************************

       * Finally we "start" the editors, this turns the textareas into

       * AreaEdit editors.

       ************************************************************************/
 

      startupDDT._ddt( "simple_example.html", "160", "calling HTMLArea.startEditors()" );
 

      HTMLArea.startEditors(areaedit_editors);
 

    	}  // end of areaedit_init()
 

	/**

	* javascript submit handler.

	*

	* this shows how to create a javascript submit 

	* button that works with the htmleditor.

	*/
 

	var submitHandler = function(formname) 

		{

	   var form = document.getElementById(formname);
 

		// in order for the submit to work both of these methods have to be

		// called.
 

	   form.onsubmit(); 

		form.submit();

		}
 

  </script>

</head>
 

<body onLoad="areaedit_init()">
 

  <h1>AreaEdit Simple Example</h1>
 

  <p>This file demonstrates a simple integration of the AreaEdit editor with a minimal

  set of plugins. Enter some content, press submit and the content will be displayed

  above.</p>

  <br>
 

  <a href="../index.html">Back to Index</a>
 

  <br>

  <hr>

  <br>
 

  <form id="editors_here" action="simple_example_landing.php" method="post">
 

    <textarea id="TextArea1" name="TextArea1" rows="10" cols="80" style="width:100%">

	 </textarea>
 

	<br>
 

	<?php

	

	

	$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required

if (!$link) {

    die('Could not connect: ' . mysql_error());

}

mysql_select_db('sank');

	

	$query="SELECT * FROM editor";

$result=mysql_query($query);

while($row=mysql_fetch_array($result))

{
 

$ing=$row['content'];
 

}
 

	// the submitHandler() function is defined in the top section and shows how to 

	// submit a form with an AreaEdit component in it from javascript.
 

	?>

	<input type="button" value="submit" onClick="javascript:submitHandler('editors_here');">

    

   Type: <select name="type" onChange="getState(this.value)">

	<option value="">Select type</option>

	<option value="1">Local Clinic</option>

	<option value="2">Company</option>

        </select> 

    

    

    

    

    

  </form>

  

  <div id="statediv">

</div>
 

<br>

<br>
 
 

<br>

</body>

</html>

Open in new window

0
Comment
Question by:whspider
  • 6
  • 4
11 Comments
 
LVL 4

Expert Comment

by:Wardy_01
ID: 24372667
Here's how i do it (generic script below).

Basic here's how it works ...

I call "ajaxCall(callingObject, url)" with callingObject being the element I wish to populate with the resulting markup and url being the url for the ajax call to be made to.

when a result is received from the server the event handler "processStateChange()" is automatically called.

note that I check 2 things ...

1. the "readyState" of the request.
2. the "status" of the request.

both values have to be correct before the call does anything.
What you will tend to find is that the state will change a few times so this  "processStateChange()" handler will get called a few times but I only action when the call is complete and the response is an acceptable 200 (try downloading fiddler as it will help you see this in more detail).

generally if you can browse to the url you pass in the ajaxcall function then this block of code will work.
I have these functions in a common scripts js file that I pull in to every project, saves writing something new every time.

Hope it helps :)
Let me know if you get stuck.
/* Function to make an ajax call */

function ajaxCall(callingObject, url) 

{

   caller = callingObject;

    

   if (window.XMLHttpRequest) 

   { // Not IE 

      req = new XMLHttpRequest();

      req.onreadystatechange = processStateChange;

      

      try 

      {

        req.open("GET", url, true);

      } 

      catch (e) 

      {

        alert(e);

      }

      req.send(null);

   } 

   else if (window.ActiveXObject) 

   { // IE

      req = new ActiveXObject("Microsoft.XMLHTTP"); 

   }

   

   if (req) 

   {

      req.onreadystatechange = processStateChange;

      req.open("GET", url, true);

      req.send();

   }

}
 

/* Function to handle results from an ajax call */

function processStateChange() 

{

   if (req.readyState == 4) 

   { // Complete

      

      if (req.status == 200) 

      { // OK response

        caller.innerHTML += req.responseText;

      }

      else

      {

        // uh oh, think it failed

        caller.innerHtml = "<span class='error'>failed.</span>";

      }

   }

}

Open in new window

0
 

Author Comment

by:whspider
ID: 24372928
Hi,

could you pls guide me where in the code i shd call this ajaxCall as am new to ajax .........
0
 

Author Comment

by:whspider
ID: 24372935
and what is this callingObject...i mean what value this will be having
0
 
LVL 4

Expert Comment

by:Wardy_01
ID: 24373059
ok ...

The way ajax works is that the user does something on the page (eg click on something) then you make a function call that posts a request to the server without postback the entire page ( .NET cals this a "postback").

AJAX calls are known as "Callbacks" because they make a call to something specific without posting everything back.

Basically try doing this on any aspx page ...

Note: other code omitted here ...

<body onLoad="ajaxCall("ajaxresult", "http://localhost/yourAjaxCalledPage.aspx");">
     <div id="ajaxresult" />
</body>

What should happen is tha when the body tag loads it makes an ajax call to the url "http://localhost/yourAjaxCalledPage.aspx" also passing the parameter "ajaxresult".

When the server returns the rendered page to the ajaxobject the function processStateChange() will be called. and the div with id "ajaxresult" will be grabbed and populated with the ajax result.

I have however just noticed that I copied out a sub portion of my js file and missed the "caller" declaration here's a new version with that caller declaration included and some script tags :)

Dump this in to the page that needs to make the ajax call (inside the body tag)  .....

<script type="text/javascript">
 

var caller;
 

/* Function to make an ajax call */

function ajaxCall(callingObject, url) 

{

   caller = callingObject;

    

   if (window.XMLHttpRequest) 

   { // Not IE 

      req = new XMLHttpRequest();

      req.onreadystatechange = processStateChange;

      

      try 

      {

        req.open("GET", url, true);

      } 

      catch (e) 

      {

        alert(e);

      }

      req.send(null);

   } 

   else if (window.ActiveXObject) 

   { // IE

      req = new ActiveXObject("Microsoft.XMLHTTP"); 

   }

   

   if (req) 

   {

      req.onreadystatechange = processStateChange;

      req.open("GET", url, true);

      req.send();

   }

}

 

/* Function to handle results from an ajax call */

function processStateChange() 

{

   if (req.readyState == 4) 

   { // Complete

      

      if (req.status == 200) 

      { // OK response

        caller.innerHTML += req.responseText;

      }

      else

      {

        // uh oh, think it failed

        caller.innerHtml = "<span class='error'>failed.</span>";

      }

   }

}
 

</script>

Open in new window

0
 

Author Comment

by:whspider
ID: 24373219
i already have <body onLoad="areaedit_init()"> on the body tag..... can i include this also or what?

and one more thing what is the difference between the one u gave and the one i have used already.

i mean the following script......


function getXMLHTTP() { //fuction to return the xml http object
            var xmlhttp=false;      
            try{
                  xmlhttp=new XMLHttpRequest();
            }
            catch(e)      {            
                  try{                  
                        xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  catch(e){
                        try{
                        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                        }
                        catch(e1){
                              xmlhttp=false;
                        }
                  }
            }
                   
            return xmlhttp;
    }
      
      function getState(typeId) {            
            
            var strURL="findtype1.php?type="+typeId;
            var req = getXMLHTTP();
            
            if (req) {
                  
                  req.onreadystatechange = function() {
                        if (req.readyState == 4) {
                              // only if "OK"
                              if (req.status == 200) {                                    
                                    document.getElementById('TextArea1').value=req.responseText;                                    
                              } else {
                                    alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                              }
                        }                        
                  }                  
                  req.open("GET", strURL, true);
                  req.send(null);
            }            
      }
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:whspider
ID: 24373319
i found where the prob is actually in.....

its in this place <body onLoad="areaedit_init()"> this is the code which loads the editor......

if i remove this on load then my editor tools goes off and only the text area is displayed....and am gettin values inside the text area.once i paste back the code i get the editor tools back but could not insert values to text area
0
 
LVL 4

Expert Comment

by:Wardy_01
ID: 24373329
I'm not exactly a javascript genius myself but reading through your script then reading mine I think yours has some logical errors in it (although I could be wrong).

Being a C# developer I'm not used to embedding function declarations inside function declarations like yours does so I can't quite guarantee I got a full understanding on the flow of your version.

The actual call is made here on your script ...

                  req.open("GET", strURL, true);
                  req.send(null);

... those 2 lines are right at the very end of the script ... surely you make the request earlier on then deal with the response, which is more inline with how my script works.

Also ...

strURL >> ??? i'm not entirely sure if you can use relative links (although you probably can) so I usually make absolute link based calls in my ajax calls.

In theory if you were to edit the function "areaedit_init()" adding in a call to your function "getState(typeId)" this should yield the same result assuming you have an element with the id "TextArea1" on your page.

If not then it might be here ...

document.getElementById('TextArea1').value=req.responseText;

try this instead ...

document.getElementById('TextArea1').innerHTML = req.responseText;

....

It looks as though your script is pretty much the same as mine everywhere else.
try opening up the ajax called url in your browser findtype1.php?type="+typeId   ... what do you get ?
0
 

Author Comment

by:whspider
ID: 24373651
the problem is in <body onLoad="areaedit_init()">

is there any other way where i can place areaedit_init()" coz the prob is in this place only
0
 
LVL 4

Expert Comment

by:Wardy_01
ID: 24373813
I couldn't say .. i don't know what this function does.
0
 

Author Comment

by:whspider
ID: 24384634
is there any other text editors where i can combine ajax values
0
 
LVL 16

Accepted Solution

by:
hankknight earned 500 total points
ID: 24449425
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

705 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

13 Experts available now in Live!

Get 1:1 Help Now