We already know a way to call controller methods in javascript, i.e. Remote Action. Now the question is, does another method exists? Yes, we can call controller methods through AJAX. Let us know more about apex in ajax.

Prereqisites

You must include following lines of script in your code:

<script src="/soap/ajax/42.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/42.0/apex.js" type="text/javascript"></script>

Apex in AJAX

First of all, you have to expose an apex class as soap service.

–> The class should be defined as global.
–> webservice keyword and static defination modifier should be added. Note: The webservice keyword gives global access to the method it is added.

Refer to the code below for understanding it better:

global with sharing class myClass { 
    webservice static Id makeContact(String lastName, String a) {
        Contact c = new Contact(LastName = lastName, AccountId = a);
        insert c;
        return c.id; 
    }
}

Now the code for Visualforce Page:

<apex:page >    
    <script src="/soap/ajax/42.0/connection.js" type="text/javascript"></script>
    <script src="/soap/ajax/42.0/apex.js" type="text/javascript"></script>
    
    <!--Container-->
    <div id="contactId">
        
    </div>
    <script type="text/javascript">
    	//Establish the connection
        sforce.connection.sessionId = '{!$Api.Session_ID}';
    
    	//Create account through AJAX
        var account = new sforce.SObject("Account");
        account.Name = 'Test Account';        
        account = sforce.connection.create([account]);
        var result =  unescape(JSON.stringify(account));
        var accountId = result.substring(result.indexOf("id:'")+9,result.indexOf("id:'")+27);       
        console.log(JSON.stringify('accountId: '+accountId));
    	
    	//Call the method through AJAX
        var id = sforce.apex.execute("myClass","makeContact",{lastName:"Smith",a:accountId});    	
        console.log(JSON.stringify('id: '+id));
    	document.getElementById('contactId').innerHTML = 'Contact Id: '+id;
    </script>
</apex:page>

Output

Here is the output:
apex in ajax

Support

That’s all about how to use Apex in AJAX, for any further queries feel free to contact us at:
https://wedgecommerce.com/contact-us/
Or let us know your views on how to make this code better, in the comments section below.

 

Leave A Reply

Please verify that you are not a robot.

Tell us about Your Company

How can we help you with your business?




    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home