Salesforce 0 Basic Learning (86) Ajax Toolkit (used with the VF page and JavaScript action)

Source: Internet
Author: User
Tags soap try catch

Ajax Toolkit Reference Documentation: Https://resources.docs.salesforce.com/212/latest/en-us/sfdc/pdf/apex_ajax.pdf

In the project, we sometimes use JavaScript for some SOQL or DML operations on a custom button or action, sometimes to get the relevant data in the VF page for logical processing, or to perform a simple DML operation, then use the Ajax Toolkit.

Not all scenarios are suitable for AJAX toolkit because AJAX Toolkit manipulate data information on the browser side, perform complex logic, or affect the performance of the front end for large amounts of data processing. Can be used under the following scenarios (not limited to the following):

    • Display or update a single piece of data
    • Show one or two columns of information in some data
    • Execute Simple business logic

Because it is used on the browser side, it is best to ensure fewer data volumes and less business logic. Here are two ways to do AJAX Toolkit introduction: Vf/javascript Action

Ajax Toolkit can be divided into three steps: Link Ajax Toolkit API, embed API call, and process the results. The next two steps are then kneaded into one step.

I. Linking to the AJAX Toolkit API

VF: The introduction of JS in the page, where 42.0 represents version, this value represents the revision number of the current connection.js. You can also set it to 41.0, 40.0 and so on.

type= "Text/javascript" ></script><script>sforce.connection.sessionId= ' {! GetSessionID ()} ';//todo</script>

OnClick javascript: reference {!requirescript ("/soap/ajax/42.0/connection.js")}

When the introduced JavaScript executes, toolkit is loaded and creates a global object sforce.connection, which allows you to access all of the API call and AJAX Toolkit Toolkit methods. The toolkit supports all SOAP API calls.

Available Core API Introduction Link: https://developer.salesforce.com/docs/atlas.en-us.212.0.api.meta/api/sforce_api_calls_list.htm

Two. Embed API call in JavaScript and perform results processing

Ajax Toolkit supports both synchronous and asynchronous invocations.

The difference between synchronous and asynchronous calls is that when a request is sent to the server side, the synchronous call needs to wait until the server side returns the result and post-processing the result, and the asynchronous call can proceed with other processing when the request is sent to the server, and then the result is processed when the server has a call to return the result. Asynchronous calls need to add a parameter to the API call to do the function processing of the calling back.

Synchronous Call Format:
Sforce.connection.method ("Argument1", "Argument2",...);

Asynchronous invocation Format:
Sforce.connection.method ("Argument1", "Argument2",..., "callback_function");

Synchronous and asynchronous exceptions are handled as follows because of the possibility of an exception being called:
Synchronous exception handling to catch exceptions by using a try catch at the call

Asynchronous exception handling provides an OnFailure configuration for asynchronous callback result, and when an exception occurs, the OnFailure configuration method is executed, and the Onsuccess method is executed successfully
Because the asynchronous invocation is the result of when the client is going to be processed, when the background processing is particularly slow, the front-end wait time is very unfriendly, the asynchronous invocation provides a timeout configuration property to set the maximum asynchronous invocation time, in milliseconds, with a minimum value of 1
Full Asynchronous invocation format
var callback = {onsuccess:handlesuccess, onfailure:handlefailure,timeout:1000};
function handlesuccess (result) {}
function Handlefailure (error) {}
Sforce.connection.query ("Select name from Account", callback);

AJAX Toolkit Call regardless of what type of data field is currently being searched in the table structure, the data type returned by using AJAX Toolkit query is of type string and the value obtained is null if the search field stores value NULL in the database , if this field is not currently searched, but there is a reference to it in the foreground JS, the value is undefined.

In addition to CRUD for data, AJAX Toolkit supports a number of operations, such as submitting approvals/getting sobject and field related metadata information/sending messages via schema.

Example of synchronous invocation:

Https://developer.salesforce.com/docs/atlas.en-us.ajax.meta/ajax/sforce_api_ajax_more_samples.htm

Asynchronous Invocation Examples:

Https://developer.salesforce.com/docs/atlas.en-us.ajax.meta/ajax/sforce_api_ajax_more_samples_asynch.htm

We also sometimes need to invoke the methods of the related classes. If you need to invoke the methods of the apex related classes, you need to introduce apex.js

VF notation: <script src= "/soap/ajax/41.0/apex.js" type= "Text/javascript" ></script>

Action notation: {!requirescript ("/soap/ajax/41.0/apex.js")}

The method of the called class must be declared webservice, the parameter of the method needs to be a base data type, a sobject type, or a list of both data types

The JS-side invocation structure is (received if there is a result returned; If no result is returned, it does not need to be received)

var result = Sforce.apex.execute ("ClassName", "MethodName", "{param1key:param1value,param2key:param2value}");

If the calling method has no arguments, the call structure is

var reuslt = Sforce.apex.execute ("ClassName", "MethodName", "{}");

Three. For example

Requirement: The customer has more than one contact, and if no contact is selected, you are prompted to select at least one contact. The selected contact requires that the contact's mailbox must not be empty. Click the button to update the contact Is_checked__c set to True.

Create fields on 1.Contact Is_checked__c

2. Create the WebService class with the parameter ContactList and update all contact Is_checked__c in the parameter to True

Global without sharingclassContactcontroller {StaticWebService Boolean Changecontactsstatus (list<contact>contactlist) {List<Contact> updatecontactlist =NewList<contact>();  for(Contact c:contactlist) {Contact Tempcontact=NewContact (); Tempcontact.id=c.id; Tempcontact.is_checked__c=true;        Updatecontactlist.add (tempcontact); }        Try {            if(Updatecontactlist.size () > 0) {update updatecontactlist; }            return true; } Catch(Exception e) {return false; }    }}

3.Contact Create custom action, set type to list Button, tick display Checkboxes,behavor select as Execute javascript

The corresponding JavaScript code is as follows (function description: https://help.salesforce.com/articleView?err=1&id=customize_functions.htm&type= 5)

{!requirescript ("/soap/ajax/41.0/connection.js")}{!requirescript ("/soap/ajax/41.0/apex.js")}varSelectedids = {!getrecordids ($ObjectType. Contact)};varContactids = ' ';if(Selectedids.length = = 0) {alert (' Choose at least one item ');} Else{Selectedids.foreach (function(item,index) {contactids+ = ' \ ' + item + ' \ '; if(Index! = selectedids.length-1) {Contactids+ = ', ';  }  }); varContactquery = "Select id,name,email,lastmodifieddate,createddate from Contact WHERE ID in (" + Contactids + ")"; Result=sforce.connection.query (contactquery); Records= Result.getarray ("Records"); varIssuccess =true; Records.foreach (function(item,index) {if(item. Email = =NULL|| Item. Email = = ") {issuccess=false; }  })  if(issuccess) {varExecuteresult = Sforce.apex.execute ("Contactcontroller", "Changecontactsstatus", {contactlist:records}); if(executeresult) {alert (' Operate success! '); } Else{alert (' Operate failed! '); }  } Else{alert (' The Items you selected has empty email.please check it again '); }}

4. Set the test action on the account's related list (contact list)

Effect Show:

1. Do not select the case

2. Normal operation

Summary: for Ajax Toolkit, consider using this approach if the amount of data is not much and needs to be handled in the foreground. However, lightning does not support action using JavaScript, so this approach only supports classic action-mode JavaScript.

Salesforce 0 Basic Learning (86) Ajax Toolkit (used with the VF page and JavaScript action)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.