Solved

Getting started with AJAX

Posted on 2006-11-02
13
495 Views
Last Modified: 2013-12-24

 I'd like to get started using AJAX with Coldfusion, there are a bunch of libraries available.

 I'm wondering if someone can recommend one of these (or an alternative) and give me a jump start.  I kinda feel like this is choosing between VHS and Beta and I bet get started in the right direction or I may end up with a bunch of code that will get out-dated.

 Looking for a combination of simplicity, power and a user-base for documentation and support.

 How do I choose among these?

- CFAJAX (http://www.indiankey.com/cfajax/)
  A ColdFusion port of the DWR project, using JavaScript as the transport. DWR (http://getahead.ltd.uk/dwr) is an open source JAVA library that uses JavaScript and a Java Servlet to provide AJAX for Java web applications. CFAJAX stands alone, replacing the servlet with a ColdFusion include.

- ajaxCFC (http://www.robgonda.com/blog/projects/ajaxcfc/)
  A CFC-based library sharing some aspects of CFAJAX (via the DWR libraries), with Model-Glue integration


- Neuromancer (http://sourceforge.net/projects/neuromancer/) SOAP-based AJAX

- Sarissa (http://sourceforge.net/projects/sarissa/)

- SAJAX (http://www.modernmethod.com/sajax/)

- JSMX (http://www.lalabird.com/jsmx/) A very lightweight engine that started out targeted at ColdFusion, using either XML or JavaScript as transports


- Prototype (http://prototype.conio.net/)


The above links were found at:
http://www.fusionauthority.com/Techniques/4593-Using-<span%20class=
0
Comment
Question by:gdemaria
  • 4
  • 4
  • 3
  • +1
13 Comments
 
LVL 2

Accepted Solution

by:
theamzngq earned 200 total points
ID: 17863100
This may not be the type of answer you're looking for, but I think you'll do just fine writing your own javascript instead of trying to figure out someone else's library, which is bound to be more complicated than you need initially.  Ajax is actually pretty simple once you get over the learning curve (which isn't bad), and to illustrate, below is a working example in two files and a simple database.

First, create a database with three columns: ID, customerName, and customerAddress.  Put a couple of lines of data in it.

Next, make a file, named what ever you like, that contains this:

<script type="text/javascript">
     // this function creates the object which will do the work of fetching data in the background
     function createRequestObject() {
          var request_;
          if(document.all) {
               request_ = new ActiveXObject("Microsoft.XMLHTTP");
          } else {
               request_ = new XMLHttpRequest();
          }
          return request_;
     }
     // setting this variable calls the above function, creating the object and assigning it to the variable 'http'
     var http = createRequestObject();
     
     function getAddr(theID) {
          // open the page in the background, passing the id variable in the url
          // I've found that adding the date/time stuff on the end of the url helps to avoid caching of results that
          // some browers will do by making the url 'unique'.
          http.open('get', 'getAddress.cfm?id=' + theID + '&time=' + new Date().getTime());
          // there are multiple 'states of being' that this process goes through, so everytime it changes, we call this function
          http.onreadystatechange = displayAddr;
          // I believe this part ends the whole proceess (though I'm not sure about that, I've just always included it)
          http.send(null);
          }
         
     function displayAddr() {
          // if the state is 4, which means the background get process is done doing its thing...
          if(http.readyState == 4){
          // fill the div with the HTML from the background process
          document.getElementById("AddrDisplay").innerHTML = http.responseText;
          }
     }

</script>

<cfquery name="getAllcustomers" datasource="#DSN#">
   select id from customer_test
</cfquery>

<table border="1" width="100">
<cfoutput query="getAllcustomers">          
<tr><td onMouseOver="getAddr(#id#);" onMouseOut="document.getElementById('AddrDisplay').innerHTML ='';">#id#</td></tr>
</cfoutput>
</table>
Name and Address:<br>
<div id="AddrDisplay"></div>


Finally, create another file, called getAddress.cfm, with this:

<cfquery datasource="#DSN#" name="getAddr">
     select * from customer_test where id = #url.id#
</cfquery>

<cfoutput>
     #getAddr.customerName#<br />
     #getAddr.customerAddress#
</cfoutput>

The notes in the javascript section explain what is happening, hopefully in an understandable way.
0
 
LVL 2

Expert Comment

by:theamzngq
ID: 17863129
To simplify how it works:

1.  Create a div somewhere on your main page that will eventually contain data you'll retrieve in the background
2.  A javascript function will create the 'http object' that will do the work of running some other CF page in the background
3.  On a button click, or a select onChange, or whatever, call the function.
4.  The function will run your CF page in the background and produce HTML output, just as it would if you loaded it normally in a browser.
5.  Once the output is done being produced in the background, another piece of javascript puts the resulting HTML code in the DIV that you specify, which makes it 'suddenly' pop on the page without it having been reloaded.

Make more (or less) sense?
0
 
LVL 2

Expert Comment

by:theamzngq
ID: 17863160
btw, the database table name should be customer_test
0
 
LVL 24

Assisted Solution

by:dgrafx
dgrafx earned 150 total points
ID: 17865857
gdemaria
I agree whole-heartedly (is that a word) with the posts made here and just thought I'd add my 1 cent.
I get a lot of questions about ajax from customers and I tell every single one that there is no need for it.
It's not a bad thing - it's just not needed. There is nothing you can do with it that you can't do with a zero size iframe or as theamzngg says a div. Almost any html element actually.
In all applications I write - I have a zero size iframe available to all files - all the time. So anytime I need to process in this fashion I don't need to create it on the file I'm working on.
theamzngg gave you the methodology.
Users do need to have javascript enabled, but so does ajax.

good luck ...
0
 
LVL 39

Author Comment

by:gdemaria
ID: 17866719

 Thanks for your responses!

 theamzngq, I was thinking that a library would help jump start me.  They seem to have scripts for populating SELECT boxes, DIVs, etc.  Wouldn't I just have to write each one of those myself in javascript?

 dgrafx, very interesting comment.  I actually have used the hidden iFrame approach plenty of times.  I thought I was "upgrading" to a better way using ajax.   Isn't there any reason why ajax is a preferred method?

 Thanks again.
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 17866960
>>> Isn't there any reason why ajax is a preferred method?
not other than people like to get on "the latest thing".
most people don't realize that they have had the ability to do this for many moons.
Even in 2006 a lot of "developers" seem to want to stay away from javascript.
This blows my mind!
Sure - there are still people who have js disabled in their browser and you need a method to take care of them, but that mostly involves validation on form submission.
It doesn't bother me in the least that js disabled browers can't use my applications.
Even here on EE you see a lot of what I assume are the "old school" guys telling newbies to stay away from javascript.
also, it's probably a situation where amateurs are hoping to jump to the next level by simply getting a new tool.
like fusebox.
most quality developers have created a methodology - they just haven't named it.
and as time goes on - it advances and is improved.
if a newbie falls into the fuse "box" they usually can never climb out.

>>>theamzngq, I was thinking that a library would help jump start me.  They seem to have scripts for populating SELECT boxes, DIVs, etc.  Wouldn't I just have to write each one of those myself in javascript?
As you learn to write these yourself - you'll become very good at javascript which will in turn make you a better programmer.
I have a series of scripts that I throw data at.
If you want to populate a page element (or do anything else) - write your script so that you can reuse them throughout your application.
don't hard code element names, ids etc.

good luck ...
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 2

Expert Comment

by:theamzngq
ID: 17872458
gdemaria, regarding your question about populating select boxes and the like, you can do all of that using a regular CF page with a database query, just like I'm sure you do all the time.  The only difference is that you can use the method I described above to 'replace' the portion of your page that has the stale select box with a 'fresh' one; tah dah! Ajax.  In my opinion, using javascript to actually manipulate a select box's items is too much work!  Sure, I could do it, but its a lot more coding.  The method above is so much easier, and can be applied to almost anything.  Learning javascript is very valuable at any rate, and will give you so much more power over your pages.  You can do amazing things even with simple scripting like the above...
0
 
LVL 36

Expert Comment

by:SidFishes
ID: 17882528
I recently started using AJAX in some of my pages. I've got a nice little answer wizard that sits on every page so customers can get an answer to any question without leaving the page...to me that's an appropriate use of the technology

I had a look a CFAJAX and saw that there was a lot of chatter about major security holes. May be fixed now but don't think so

Checked out AJAXCFC and works great except it doesn't play nice with Fusebox so that was out.

Ended up using JSMX. very nice and easy to use.


0
 
LVL 39

Author Comment

by:gdemaria
ID: 17883569

 Thanks Sid,
 What option did you choose with JSMX to return data from the server?  "classic mode" using javascript?
 Have you ever used the hidden iFrame approach?  If so, can you compare?
0
 
LVL 36

Expert Comment

by:SidFishes
ID: 17883738
I'm using WDDX mode as I'm returning data from cfc's..which is natively returned in wddx format so there's nothing for me to do but set my data  into innerHTML divs... It's the easiest for someone whose not a JS wiz and I'm certainly not...but getting better

did not use iframes so no help there...
0
 
LVL 39

Author Comment

by:gdemaria
ID: 17883851

 any way you may be able to post a little code as samples?  :)
0
 
LVL 36

Assisted Solution

by:SidFishes
SidFishes earned 150 total points
ID: 17884337
sure ... make sure you include engine.js in any page with a call

<script src="#request.consumerurl#engine.js"></script>

<cfoutput>      

<script type="text/javascript">      

//make your AJAX call
function getFAQAnswer_request()
   {
       param = 'FAQID='+document.getElementById('topics').value;
       http('POST','#request.consumerurl#com/faqtool.cfc?method=getSingleFAQanswer',getFAQAnswer_response,param);
   }

function getFAQAnswer_response(obj) {
//parse the response
              document.getElementById('faq').innerHTML = obj.faqtitle;
              document.getElementById('answer').innerHTML = obj.faqtext;
         document.getElementById('externallink').innerHTML = "<a href=" +  obj.externallink + " target=\"_blank\">" + obj.externallinkdescription + "</a>";                        
       }

</script>


<div id="wizard">
                                    
<SELECT  name="topics" id="topics" >
<option value="">-- Select Topic --</option>
</SELECT><p>
<input id="topicsubmit" type="submit"oncLick ="getFAQAnswer_request();" value="Show Answer">                                    
</p>
<br>
<div id="answerarea">
<h3 id="faq"></h3>
<h3 id="answer"></h3>
<h3 id="externallink"></h3>
</div>
</div>            
</cfoutput>



and faqtool.cfc

      <cffunction name="getSingleFAQanswer" hint="I Return a single FAQ answer"
                        returntype="query" access="remote">
      <cfargument default="" name="FAQID">      
            <cfquery name="singleFAQanswer" datasource="#request.dsn#">
                  Select * from tblfaqanswers
                  Where FAQID = <cfqueryparam cfsqltype="cf_sql_integer"
                                          value="#FAQID#">
            </cfquery>
            <cfreturn singleFAQanswer>
      </cffunction>



shows the basics...I snipped a bunch of code out so hope I didn't break anything...

Couple of things to watch...

you need to add access="remote" to any cfc or method that you want to access via ajax.
and all the returned object nodes are converted to lowercase no matter what case the field names are in the wddx packet

ie: wddx packet fieldNames='FAQTEXT" must be referenced as obj.faqtext and not obj.FAQTEXT (this one drove me nuts for a while)

note that param value is FAQID and FAQID is the cfargument

If you are going to get into ajax I highly recommend picking up a http stream analyzer like HTTP Analyzer from IEInspector.com or firebug extension for firefox...it's the only way you can usefully debug what is going on with your calls. For security reasons, JSMX has very generic error messages and are no help (which is a good thing)


0
 
LVL 39

Author Comment

by:gdemaria
ID: 17938532

 Thanks everyone for a lot of great information.  I'm sure this will make good browsing for future readers.


 I ended up sticking with my iFrame approach.  It's incredibly easy.  I use a fusebox style coding in my current application, so I created a new  indexRS.cfm (RS for remote service).    The indexRS captures whatever action I select and instead of drawing it to the screen, places it into a string and uses javascript to place it into the DIV I indicated by the DIV's ID.   I don't have to do any special coding once this is in place, I just write Coldfusion as I always do and refer to a different index file (indexRS.cfm) when I want to use remoteService.

 
 That's just the option I chose since I already had much of it, I think the ajax information on this page will be very useful to others.  Points shared.  Thanks again!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Article by: kevp75
Hey folks, 'bout time for me to come around with a little tip. Thanks to IIS 7.5 Extensions and Microsoft (well... really Windows 8, and IIS 8 I guess...), we can now prime our Application Pools, when IIS starts. Now, though it would be nice t…
If you don't have the right permissions set for your WordPress location in IIS, you won't be able to perform automatic updates. Here's how to fix the problem.
The purpose of this video is to demonstrate how to connect a WordPress website to Google Analytics. This will be demonstrated using a Windows 8 PC Go to your WordPress login page. This will look like the following: mywebsite.com/wp-login.php :…
The purpose of this video is to demonstrate how to manually back up a WordPress Database. This will be demonstrated using a Windows 8 PC. The Host used will be IPage.com Log into your Hosting account. IPage will be used for demonstration : Locat…

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

19 Experts available now in Live!

Get 1:1 Help Now