+ 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
 

Sanjay33Sanjay33

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

some useful info here for using remoting.

http://www.salesforce.com/us/developer/docs/pages/Content/pages_js_remoting.htm

B01000111B01000111

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