Hi, in this post i will explain you about Ajax Toolkit in salesforce. How and when to use Ajax toolkit.
So This post is divided into three section :
- Ajax toolkit Explaination(Defination)
- When to use ajax toolkit
- Ajax toolkit Example
- What is AJAX Toolkit
Ajax Toolkit is a JavaScript wrapper around the API . Ajax Toolkit Embed API calls and processes, such as within a Visualforce page, or custom button .Salesforce offer AJAX tool kit to run javascript and allowing user to make a connection with Salesforce and query salesforce from javascript, the data in-return can be handled in own fashion to be displayed on the page.
2 . When to use AJAX Toolkit
- AJAX Toolkit is used when you need to working with small amounts of data.
- Display or modify a single record.
- Display two or three fields from many records
- Perform one or more simple calculations, then update a record.
3. Ajax toolkit Example
Requirement : On click of custom button in contact details page call a controller function and then perform some operation on the object by using connection.js .
So to fulfill this requirement we follow the below steps :
- Create a custom button . And add this custom button to contact layout follow the steps in the image to create a custom button .
2. Write an apex class and the function that we call using sforce.apex.execute method on button click
here is the apex class example code.
global class StopOtherContacts {
webservice static string updateContact(String contactid)
{
contact thiscontact = [select id,Client__c,accountid from contact where id =: contactid];
list<contact> contacts;
//if(thisContact != null && thiscontact.accountid != null && thiscontact.Client__c != null)
contacts = [select id, Lead_Status__c, Client__c from contact where Client__c =: thisContact.Client__c and accountid =: thiscontact.accountid and id!=:thiscontact.id];
if(contacts != null)
{
for(contact contact:contacts){
contact.Lead_Status__c = 'Not The DM';
}
update contacts;
}
if(contacts != null)
return 'True';
else
return 'False';
}
}
3. Now Call this class on button click by the help of sforce.execute method . write the below code snippet on javascript portion in your custom button .
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
var cnnId='{!Contact.Id}'
var result = sforce.apex.execute("StopOtherContacts","updateContact",{contactid:cnnId});
if ( result == 'True'){
txt="Contacts Updated Successfully.\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
} else {
txt="There was an error on this page.\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
//sforce.debug.trace=true;
window.location.reload();
Views: 0

