Thursday, December 30, 2010

ColdMVC: AJAX call

Trying to make ajax calls with ColdMVC was a little difficult for me because I struggle with routes, but I found a way. Here is what I did to make an AJAX call with ColdMVC.

First I created a function on a Controller so I can return "hi" back from the AJAX call. Notice I have @view json.cfm above the function. Since ColdMVC uses routes I need to send the data to a view and cfoutput it on the page.

TestController

/**
* @accessors true
* @extends coldmvc.controller
*/
component {

/**
@view json.cfm
*/
function testMethod(){
params.json = "hi";
}

}


Here is json.cfm. All that I do with it is output the variable "json".

json.cfm

<cfoutput>#params.json#</cfoutput>


And lastly I preform my AJAX call using jQuery. In the url setting of jQuery.ajax() I just link to the controller. In my case, my controller's name is TestController, so my route with just be "test" and then I can change out the method. In my case I am calling the "testMethod" on the controller.

ajaxCall = function(){

jQuery.ajax({
url:"#coldmvc.link.to('/test')#/test?returnformat=json",
type:"GET",
success:function(data){
jQuery("body").html(data);
}
});
};


If you want to return json back just go to json.cfm and wrap params.json in SerializeJSON(). Then in your ajax call, do jQuery.parseJSON(). This is the only way I can think of right now to make an ajax call with ColdMVC, if there are any other techniques I would be more then happy to listen.

4 comments:

  1. Here's a slightly simpler approach:

    ajaxCall = function() {
    $('body').load('#linkTo("/test/test", "format=json")#');
    }

    component {

    /**
    @formats json
    */
    function testMethod(){
    params.json = "hi";
    }

    }

    If you use ?format=json in the URL, ColdMVC will automatically output the serialized params, allowing you to skip the json.cfm view "middle-man". However your method must allow the format using an @formats json annotation. The default accepted format for all methods is html.

    JSON isn't automatically allowed for all methods since the entire params scope is serialized, which could lead to over-exposure of data if objects containing sensitive data could be serialized for any URL just by specifying a format parameter.

    ReplyDelete
  2. Tried it and it did work. It returns me the params in json text, but i can't seem to access them in JS now as a JSON object. I've tried jQuery.parseJSON(data.result); but still no luck. Keeps returning null.

    ReplyDelete
  3. Nevermind. I am idiot. I should be doing jQuery.parseJSON(data); instead of jQuery.parseJSON(data.result);

    Thanks, it's alot easier to use the @formats annotation.

    ReplyDelete
  4. No problem.

    This is the reason why I need to create some documentation...

    ReplyDelete