Skip to content

Instantly share code, notes, and snippets.

@neokoenig
Created July 31, 2014 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save neokoenig/5d5305c6aaf2c5c24c98 to your computer and use it in GitHub Desktop.
Save neokoenig/5d5305c6aaf2c5c24c98 to your computer and use it in GitHub Desktop.
cfwheels simple ajax example
<!--- My Partial --->
<cfoutput>
<h3>I've been called remotely</h3>
<p>The time is #timeformat(now(), "HH:MM")#</p>
</cfoutput>
<cfcomponent extends="controller">
<cffunction name="init">
<cfscript>
provides("html,json");
filters(through="_isValidAjaxRequest", except="index");
</cfscript>
</cffunction>
<!--- This is called remotely;
isAjax() just confirms this is an ajax request;
renderPartial() returns the HTML of the partial without further processing
--->
<cffunction name="getpartial" access="public">
<cfset renderPartial("time")>
</cffunction>
<!--
this is another way of doing the same thing without a partial
renderWith is useful to return simple strings etc.
--->
<cffunction name="gettext" access="public">
<cfset thetime="Returned with renderWith: " & timeFormat(now(), "HH:MM")>
<cfset renderWith(thetime)>
</cffunction>
<!--- This is called for every request to the AJAX controller via filters() --->
<cffunction name="_isValidAjaxRequest" access="private">
<cfif !isAjax()>
<cfthrow message="Not an ajax request!">
</cfif>
</cffunction>
</cfcomponent>
<!---
I've used a cfwheels helper here, but this could just as easily be <a href="/ajax/getpartial" class="callremotedata">Click</a>
--->
<cfoutput>
#linkTo(text="Get the time via Partial", controller="ajax", action="getpartial", class="btn btn-primary callremotedata", params="format=json")#
#linkTo(text="Get the time via renderText", controller="ajax", action="gettext", class="btn btn-primary callremotedata", params="format=json")#
</cfoutput>
<!---
This is the element the result of the partial will be insert into
--->
<div id="result"></div>
<script>
$(document).ready(function(){
// Click handler for the ajax button
$(".callremotedata").on("click", function(e){
// This is the URL which the ajax request will fire at; I'm grabbing the HREF of the button as it's more flexible
var remoteURL=$(this).attr("href");
// The actual AJAX call
$.ajax({
url: remoteURL,
// This function fires when the request is successful: it takes the result of the ajax request and replaces the HTML in the target <div>
success: function(result){
$("#result").html(result);
}
});
// This just stops the <a> tag firing as a normal tag.
e.preventDefault();
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment