+ Start a Discussion

Call Apex Controller Method using JQuery



I have added following Controller and Apex page and when I open the Apex page in browser using https://ap1.visual.force.com/apex/AjaxResponder?q=GetAJAX, value for the parameter "q" i.e. "GetAJAX" is displayed in browser.


--Start : Source Code for Controller class

public class AjaxRespController {
    String searchResult;
    /** invoked on an Ajax request */   
    public void doSearch() {
        Map<string,string> params = ApexPages.currentPage().getParameters();
        // Do SOQL query to see if there are any records !
        //List<Contact> records = getRecords(params.get('q'));
        searchResult = params.get('q');      
    // Returns the JSON result string
    public String getResult() {
        return searchResult;

--End : Source Code for Controller class


--Start : Markup for Visualforce page

<apex:page controller="AjaxRespController"  action="{!doSearch}"
contentType="text/plain; charset=utf-8" showHeader="false" standardStylesheets="false" sidebar="false">

--End : Markup for Visualforce page


I created Home Page Component and added following following JQuery to call Apex Controller Method, but request is failing.

Also tried using relative path for the URL i.e. "/apex/AjaxResponder". But still reques is failing. Please guide me in resolving this issue.


-- "CallApexController" is called on click of a button which is added in page body using JQuery "Append" method in "Body" tag.


var j$ = jQuery.noConflict();


function CallApexController() {
        type: "GET",
        url:"https://ap1.visual.force.com/apex/AjaxResponder?q=" + searchKeyword,
        contentType: "plain/text; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: AjaxSucceeded,
        error: AjaxFailed

function AjaxSucceeded(result) {

function AjaxFailed(result) {






you can better try using web service or remoting, it's quite easy and powerful.

some useful info here for using remoting.



calls to Web Services are limited ( salesforce has limit for this :( ) and remoting is so bad