Edits – Nov 2011
This post was written long back in Feb 2010, since then force.com platform is drastically upgraded/changed. The illustration indicated in the post below can be achieved very easily using new platform features like Javascript Remoting.
So if you are planning to use JSON with jquery/javascript, more fun way to achieve the same is remoting, this post is a good guide to start with remoting & jquery :
http://www.tgerm.com/2011/03/javascript-remoting-jquery-templates.html
Abstract
This post is for those who want to make AJAX calls in visualforce using 3rd party JavaScript frameworks like jquery, yui , dojo etc. Though most the times the built in visual force Ajax works pretty well and you don’t need to make your hands dirty by doing this. But but but, there are couple of occasions when its required for ex.
You are working on a complex DOM structure i.e. there is nesting of HTML elements in a manner not easy to deal with Visual force tags.
You want to update the DOM client side, this requires some Ajax calls to query server side data.
Visualforce Ajax gives you a way to do this by calling “rerender”, but you want more control on request and response data.
Design
Following is the high level design of custom Http request response in salesforce

So this design comprises of following elements
A dedicated Visualforce page for receiving inbound Ajax http requests. Lets call this page “AjaxResponder”
This page can return either “JSON” or “XML” response.
For doing all server side logic an Apex Controller is required that will do the SOQL/SOQL queries. Lets call this “AjaxRespController”
A client page to test and do all the Ajax calls. Lets call this “AjaxClient”
Implementation (Apex Visualforce code)
We will start with the Server Side code first i.e. AjaxResponder(Visualforce Page) and AjaxRespController (Apex Controller). At last you can find code for the Ajax client page.
AjaxResponder(Visualforce):
Simple visualforce page. Please note that you need to add following apex:page headers. This is because we don’t want any other HTML markup from salesforce in Ajax response.
showHeader = false
standardstylesheets = false
sidebar = false
Apart from this you need to set the content type for JSON response, so add the header contentType=”application/x-JavaScript; charset=utf-8″. For printing JSON text in visualforce page, just create a string attribute in your controller, for this demo I created “result”, and add this to VF code like this {!result}.
<apex:page controller="AjaxRespController" action="{!doSearch}"
contentType="application/x-JavaScript; charset=utf-8" showHeader="false" standardStylesheets="false" sidebar="false">
{!result}
</apex:page>
AjaxRespController (Apex Controller):
Controller will check the Ajax request parameters and will do the SOQL query stuff. In the code snippet below doSearch() method is called on Ajax call. We have used JsonObject, this is a class adopted from json.org by Ron Hess. You can get it from here. Apart from this there is a getter method called “getResult” it returns the JSON response back to visualforce.
public class AjaxRespController {
public JsonObject json {get;set;}
/** invoked on an Ajax request */
public void doSearch() {
Map<string,string> params = ApexPages.currentPage().getParameters();
json = new JsonObject();
// Do SOQL query to see if there are any records !
List<Contact> records = getRecords(params.get('q'));
if (!records.isEmpty()) {
// Jsonify the results !
List<JSONObject.value> values = new List<JSONObject.value>();
for (Contact c : records) {
JSONObject cjson = new JSONObject();
cjson.putOpt('name', new JSONObject.value(c.Name));
cjson.putOpt('email', new JSONObject.value(c.email));
values.add(new JSONObject.value(cjson));
}
json.putOpt('contacts', new JSONObject.value(values));
}
}
// Does the SOQL query, using Ajax request data
public List<Contact> getRecords(String contactName) {
List<Contact> records = new List<Contact>();
if (contactName != null && contactName.trim().length() > 0){
// Protect from SOQL injection
String contactNameToFilter = '%' + contactName + '%';
records = [select id, name, email from contact where Name like :contactNameToFilter];
}
return records;
}
// Returns the JSON result string
public String getResult() {
return json.ValuetoString();
}
}
Ajax Client (Visual force):
This page is one that presents the user interface to query the results via custom Ajax. The code below is simple markup to do Ajax calls and show JSON response. Please note here in code that to make Ajax calls work, you need to pass an extra param “core.apexpages.devmode.url” with value ‘1’. This is required because without this param the visualforce page is opened in an iframe and you get the iframe code wrapped in other crappy html.
<apex:page showHeader="true" standardStylesheets="true" >
http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
<apex:sectionHeader title="Ajax Client Demo" />
<apex:pageblock >
<apex:pageBlockSection title="Query Console">
<form id="qform">Query String <input type="text" id="query" />
<input type="button" onclick="search()" value="Search Contacts " /></form>
</apex:pageBlocksection>
<apex:pageBlockSection title="Ajax Console">
<h1>Status</h1>
<pre id="status" style="font-size: 16px" />
<h1> JSON Response </h1>
<div id="response" style="font-size: 16px;width: 300px;font-family: monospace; font-stretch: expanded" />
</apex:pageBlocksection>
</apex:pageblock>
</apex:page>
Here is this UI in action


Here is the VIDEO SCREENCAST !
You can copy all the code snippet above and run it directly on your salesforce org. Just replace “[NODE]” in following URL by yours.
Comments (27)
Anonymoussays:
February 22, 2010 at 6:56 pmBrilliant approach. Nice job!
Anonymoussays:
July 20, 2010 at 2:29 pmSo this is cool, but as far as I can tell that implementation of JSONObject is open to injection attacks if a malicious user places “; maliciouscode(); str = ” in a contact name.Have you tested this and found it to be secure? I'd love to generate JSON in apex but haven't found a secure way to do it yet.
Anonymoussays:
July 20, 2010 at 2:45 pm@Terra thanks for appreciation. Sorry comment emails were not enabled in Feb, so I can't see your comment.@Mat Interesting point, I guess if we are accepting user input, even if thats having malicious code. The Apex SOQL query like this will save us on server sideString contactNameToFilter = '%' + contactName + '%';records = [select id, name, email from contact where Name like :contactNameToFilter];But yes, I have never generated any JSON output, that carries user provided strings directly. As here, the JSON output is created from the SOQL query results. So it seems safe to me, what do you say ?
Anonymoussays:
August 11, 2010 at 2:09 amVery useful. Link to jQuery CDN is bad though (should be all lowercase).
Anonymoussays:
August 11, 2010 at 5:23 amThanks @Joel !Fixed the CDN URL, its strange URLs are usually case-insensitive !
Anonymoussays:
August 12, 2010 at 7:57 pmI think you'd still want to do String.escapeSingleQuotes(contactName) in your code
Anonymoussays:
August 13, 2010 at 5:52 am@Joel if I am not understanding wrong and escaping you pointed is for SOQL injection, I guess the code is already safe from that. This is because the SOQL query is not a Stringlike 'Select x,y,z from A where ' rather its an Apex statement [Select x,y,z from A where]. The same approach is suggested in SFDC docs(check section 'SOQL Injection Defenses') too here : http://www.salesforce.com/us/developer/docs/apexcode/Content/pages_security_tips_soql_injection.htm
Anonymoussays:
August 15, 2010 at 5:29 amCool man was very helpful.I did know that we are having something like JSONObject in salesforce i had my own custom logic to create that.
Anonymoussays:
August 15, 2010 at 6:05 am@Sankky glad you find it useful. Thats true JSONObject is not yet part of standard Apex library(though it should be !), its open source and came out from development evangelists of Salesforce.
Anonymoussays:
August 16, 2010 at 7:28 pm@Abhinav,You are right. I was looking at my code which required a bit more tinkering than yours.Here is the result:http://snipplr.com/view.php?id=39158
Anonymoussays:
August 17, 2010 at 2:14 am@Joel, saw your code and blog post on this too. I'm glad you cracked this.
Anonymoussays:
September 9, 2010 at 5:44 amAbhinav, thanks for the informative post. I took a different approach – I integrated Salesforce objects into a Store subclass in ExtJS by way of the AJAX Toolkit. I assume something similar is possible in jquery, etc. Any thoughts on the JSON page/controller approach vs making web services calls via connection.js?Abhinav, thanks for the informative post. I took a different approach – I integrated Salesforce objects into a Store subclass in ExtJS by way of the AJAX Toolkit. I assume something similar is possible in jquery, etc. Any thoughts on the JSON page/controller approach vs making web services calls via connection.js?Short post with link to code here: http://jefftrull.livejournal.com/2758.html
Anonymoussays:
September 9, 2010 at 6:22 am@JeffRey, thats very true we can use Ajax Toolkit for sure for implementing Visualforce Jquery Ajax. We used Ajax toolkit a couple of times in past. Once for doing describe calls in JS and saving us from governor limits in Apex :)From comparison stand, I would say if we don't need to do something complex(like do a straight SOQL) prior handling JSON response, then for sure Ajax toolkit is good option. But, if we need to go a little more complex i.e. * Create complex SOQL involving datetime conditions. Date/Time/Timezone SOQL is always safe in Apex.* Aggregating results from complex calculations, like 2-3 different SOQLs OR prepare a custom JSON for easy/direct spoon feeding Jquery/Ext JS componentsThen having such VF+Ajax setup is good, as we can easily go little more complex easily in Apex and visualforce rather playing hard in Javascript. This was my scenario in one project, our XML response was driven out of some complex Apex calculations based on custom settings etc.But yes, 100% agreed with your point. We should for sure use Ajax toolkit for some cases. I will try coming up with a blog post on this. Thanks for sharing the ExtJs + Ajax Toolkit link, I will go thru it.
Anonymoussays:
October 6, 2010 at 8:35 amhow to do this with jquery-ajax
Anonymoussays:
October 6, 2010 at 9:14 am@giri I haven't tried this code snippet, but hopefully will work with $.ajax().$.ajax({ type: “GET”, url: “{!$Page.AjaxResponder}”, data: “core.apexpages.devmode.url=1&q=” +$('#query').val(), dataType : 'json', success: function(data){ $(“#response”).html(JSON.stringify(data)); } });
Anonymoussays:
March 22, 2011 at 5:55 amHello abhinav it is good approach. I want to build jstree and in that i want to use JSON object how can i use that ? reply me : minkesh422000@gmail.com
Anonymoussays:
March 22, 2011 at 6:11 amThanks Minkesh,I am not clear on your question, the whole post is about creating JSON object only. So you can create required JSON structure for JSTree. Let me know if you still have more queries.
Anonymoussays:
March 22, 2011 at 11:42 amI have tried this but only received Error on page while accessing the code in IE.But the error is not displayed in Mozilla but i dont find the result.any help please?sriram
Anonymoussays:
March 22, 2011 at 2:19 pmSriram, can you please share the error you are getting in IE. Also check the error console in Mozilla for getting error details.
Anonymoussays:
March 23, 2011 at 6:55 amHi abhinav ,thanksfor the reply.I got it fixed,i have used the latest jquery Plugin (version 1.4.4) for jquery.min.js instead of version 1.3.2 and its worked awesome.
Anonymoussays:
March 23, 2011 at 7:04 amThats Great Sriram ! Using latest and greatest of library mostly works good 🙂
Anonymoussays:
November 8, 2011 at 8:36 pmHow do you display a XML response?
Anonymoussays:
November 9, 2011 at 3:45 amShriram you can change apex: page tag like this <apex:page controller="AjaxRespController" action="{!doSearch}"contentType=”application/xml; charset=utf-8″ showHeader=”false” standardStylesheets=”false” sidebar=”false”>{!result}
Anonymoussays:
November 9, 2011 at 2:01 pmHello,i cannot save AjaxRespController, because :”Error Error: Erreur de compilation : Invalid type: JsonObject à la ligne 3 colonne 12″What can i do please ?Thank You! Emmanuel
Anonymoussays:
November 10, 2011 at 3:21 amJsonObject is a legacy class now, as winter'12 release came up with native Json parser. More details here : http://www.tgerm.com/2011/10/winter12-jsonparser-serialize.htmlIf you still want to use JSONObject class, then its available for download here : http://code.google.com/p/apex-library/source/browse/trunk/JSONObject/src/classes/JSONObject.clsApart from this, I would suggest one to use Javascript remoting to achieve the same.
Anonymoussays:
November 10, 2011 at 9:54 amThank you for your answer.so, why do i get this error message ??I just try to realise this tutorial, with the objective to understand how i can control data, with javascript, in a visualforce page. I have to say that this information isn't easy to find …Emmanuel
Anonymoussays:
November 10, 2011 at 11:52 amJSONObject in not a standard salesforce class, you need to include it. download here : http://code.google.com/p/apex-library/source/browse/trunk/JSONObject/src/classes/JSONObject.cls