+ Start a Discussion
Mike_M_2Mike_M_2 

Get JSRemoting to execute on page load

Here is the example I got, but it triggers off of ONCLICK. I want to be able to use the JSRemoting to run an APEX class which would return data and ultimately the data would be shown on the first rendering of the visualforce page. I've tried a dozen different things, but no luck. What do I need to do to this code to get the desired result ...

 

<apex:page controller="MyJSRemoting">
<script type="text/javascript">
function getAccountJS() {
var accountNameJS = document.getElementById('accountname').value;

MyJSRemoting.getAccount( accountNameJS, function(result, event)
  {
    if (event.status)
    {
        document.getElementById("{!$Component.theBlock.pbs.pbsi2.accId}")
        .innerHTML = result.Id;
        document.getElementById("{!$Component.theBlock.pbs.pbsi1.name}")
        .innerHTML = result.Name;
   }
}, {escape:true});
}
</script>


<input id="accountname" type="text"/>

    <button onclick="getAccountJS();">Get Account</button>


      <apex:pageblock id="theBlock">
        <apex:pageblocksection columns="2" id="pbs">

               <apex:pageblocksectionitem id="pbsi1">
               <apex:outputtext id="name">
               </apex:outputtext>
        </apex:pageblocksectionitem>

        <apex:pageblocksectionitem id="pbsi2">
                  <apex:outputtext id="accId">
                   </apex:outputtext>
         </apex:pageblocksectionitem>

    </apex:pageblocksection>
</apex:pageblock>
</apex:page>

 

TIA, Mike

Best Answer chosen by Admin (Salesforce Developers) 
JeffStevensJeffStevens

You might try to use the action="" keyword on the Page header.  That will call a method in the controller that is called before the constructor is called. 

All Answers

JeffStevensJeffStevens

You might try to use the action="" keyword on the Page header.  That will call a method in the controller that is called before the constructor is called. 

This was selected as the best answer
Mike_M_2Mike_M_2

Okay, I'll try that. Actually, I'm not wedded to the idea of using JavaScript, but as far as I can tell, it's the only way to invoke an APEX class from within a visualforce page. Probably not true, but I'm very new to this. 

sfdcfoxsfdcfox

The action="{!method}" attribute does just that: it calls Apex Code on the server after the page's constructor, but before rendering.

 

You can also use the constructor of your class to call other code before the page loads.

 

public class MyController {
    public MyController() {
        // Do stuff here
    }
}

Finally, when using extensions, you can also call code in their constructors:

 

<apex:page standardcontroller="account" extensions="MyExtension" ...
public class MyExtension {
    public MyExtension(ApexPages.StandardController controller) {
        // Do stuff here
    }
}

The "controller" in this case gives you access to the current record you're working on.

Mike_M_2Mike_M_2

Okay, I've ditched the JSRemoting and am now trying to use the action like this.

 

<apex:page standardController="Opportunity"
                                     extensions="OpportunityControllerExtension,JSONParserUtil"
                                     showHeader="false" renderAs="{!$CurrentPage.parameters.renderAs}"
                                     action="{!parseJSONResponse}">

 

here is the class

 

 

public class JSONParserUtil {
    //@future(callout=true)
    @RemoteAction
    public static string parseJSONResponse() {        
        Http httpProtocol = new Http();
        // Create HTTP request to send. 
    
        HttpRequest request = new HttpRequest();
        // Set the endpoint URL. 
    
        String endpoint = 'http://www.cheenath.com/tutorial/sfdc/sample1/response.php';
        request.setEndPoint(endpoint);
        // Set the HTTP verb to GET. 
    
        request.setMethod('GET');
        // Send the HTTP request and get the response. 
    
        // The response is in JSON format. 
    
        HttpResponse response = httpProtocol.send(request);
        System.debug(response.getBody());
      
        // Parse JSON response to get all the totalPrice field values. 
    
        JSONParser parser = JSON.createParser(response.getBody());
        Double grandTotal = 0.0;
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                (parser.getText() == 'totalPrice')) {
                // Get the value. 
    
                parser.nextToken();
                // Compute the grand total price for all invoices. 
    
                grandTotal += parser.getDoubleValue();
            }
        }
        system.debug('Grand total=' + grandTotal);
        return response.getBody();
    }  
    public JSONParserUtil (ApexPages.StandardController controller) {
        // Do stuff here
    }
     
}

The question is: how do I return response.getBody() to be displayed on my visualforce page?

 

thx

Mike_M_2Mike_M_2

Nevermind, I think I found some examples.

Thanks