Visualforce Salesforce jQuery Ajax, how to?
Nov 2011 – Edits
This post was written in February 2010, and the force.com platform has been drastically upgraded/changed since then. 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, remoting is a more fun way to achieve the same; this post is an excellent guide to starting with remoting jQuery.
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 of the time the built-in visual force Ajax works pretty well, you don’t need to make your hands dirty by doing this. But there are a couple of occasions when it is required, for example:
You are working on a complex DOM structure, i.e. there is nesting of HTML elements in a manner that is 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 over request and response data.
Design
Following is the high-level design of the custom HTTP request-response in Salesforce:
So this design comprises the following elements:
A dedicated Visualforce page for receiving inbound Ajax HTTP requests. Let us call this page “AjaxResponder”.
This page can return either a “JSON” or “XML” response.
For doing all server-side logic, an Apex Controller is required that will do the SOQL/SOQL queries. Let's call this “AjaxRespController”
A client page to test and do all the Ajax calls. Let's 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 the code for the Ajax client page.
AjaxResponder(Visualforce):
Simple visual force page. Please note that you need to add the following apex:page headers. This is because we don’t want any other HTML markup from Salesforce in the 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 on the visual force page, just create a string attribute in your controller; for this demo, I created “result”, and added 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):
The controller will check the Ajax request parameters and will do the SOQL query stuff. In the code snippet below, the “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” which returns the JSON response back to visual force.
public class AjaxRespController {
public JsonObject json {get;set;}
/** invoked on an Ajax request */
public void doSearch() {
Map params = ApexPages.currentPage().getParameters();
json = new JsonObject();
// Do SOQL query to see if there are any records !
List records = getRecords(params.get('q'));
if (!records.isEmpty()) {
// Jsonify the results !
List values = new List();
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 getRecords(String contactName) {
List records = new List();
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 presents the user interface to query the results via custom Ajax. The code below is a simple markup to do Ajax calls and show JSON responses. Please note here in the 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 parameter, 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>
Try for Yourself
You can copy all the code snippets above and run them directly on your Salesforce.org. Just replace “[NODE]” in the following URL with yours.
https://[NODE].force.com/apex/AjaxClient
Let’s Talk
Drop a note below to move forward with the conversation 👇🏻