Salesforce Integration

DML before Apex Callouts using Salesforce AJAX

You all might have encountered a situation where you want to update/create/delete a record (i.e, perform a DML operation) and based on it’s output would like to then make a Web Service call (may be passing some values from the previous DML operation). While doing so you would have seen an error being thrown as below :

You have uncommitted work pending. Please commit or rollback before calling out

This is due to the fact that there is a limitation in salesforce that you can’t do a DML operation and callouts in one single context. An idea was also posted about few years back in salesforce success forum but it  seems it won’t be provided/supported by them in the multi-tenant environment, in order to protect the service. There are few alternatives to achieve it but here I am going to talk about using AJAX capability of visualforce by making an internal ajax call to change the transaction before making the external callout. In short, I am trying to make 2 transactions – one for DML and second for web service call with 1 button click – so that it seems transparent to the user that they clicked only once. You can also add some status refreshes on the page so that user sees something is happening while in the backend perform DML followed by web service call.

In the below apex code, I have create 2 methods – one is creating an Account record and then the second method is calling an HTTP Rest web service which is simply an Http GET call to an external service. You can read about Apex callouts using Rest here. In the Visualforce code, I am making a call to the action method ‘createAccount’ on the click of a button and once it completes, using ajax it invokes the second action method ‘callWS’ which contains the web service calling code.

Click here for demo

Make sure you add the Http Endpoint in Remote Site Settings of your salesforce org, otherwise salesforce would throw error as it does not allows external callouts.

Feel Free to provide your valuable comments or point out any issues or scope of improvement in this post.