function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
prasad_more1.3158103303596086Eprasad_more1.3158103303596086E 

Call Apex Controller Method using JQuery

Hi,

 

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">
{!result}
</apex:page>

--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() {
    j$.ajax({
        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) {
    alert('AjaxSucceeded');
}

function AjaxFailed(result) {
    alert('AjaxFailed');
}

 

 

Thanks,

Prasad