+ Reply to Thread
Results 1 to 4 of 4

Thread: Simple PHP Salesforce Ajax Tutorial

  1. #1
    lachof is offline Junior Member
    Join Date
    Nov 2007
    Posts
    10

    Post Simple PHP Salesforce Ajax Tutorial

    Hello all, after bothering my good friend Mike several times I should (and owe) add something to this great forum.

    This is a small SF-PHP-Ajax tutorial that I put together and I hope you find it helpful , please remember that I'm not an expert so try to be as much constructive on your comments as you can. I know that this code can be optimized but the idea is to give an example on how to accomplish this.

    Saludos!!

    Lachof


    Here is a small and simple tutorial for all those that are starting to use Salesforce PHP toolkit on how to use ajax and PHP classes.
    Of course there are many way to accomplish this but the intention is to give you a guide and I encourage you to find better ways to do it.
    Even though i believe that assumption is the mother of all mess ups, I will now assume that you are a little bit familiar with the toolkit and a little bit familiar with PHP classes.

    Let’s start

    What you’ll need.

    1. I used a very simple library called JsHttpRequest it’s an easy-to-use cross-browser AJAX library with AJAX file uploading support and many other features to “ajaxise” my application, you can find information here.
      1. Basically what this library does is to take requests in a javascript and then send it to a php file with parameters if needed and then wait for the response and since we are still in javascript we can change html on the fly.
      1. This library its stored in a folder named includes.
    2. I divided my classes into BL class for all Business Logic operations and DAL class for the Data Access Layer and they are stored in a folder named classes.
    3. I have a custom field in SF called Manufacturer__c inside the Product2 object. What we are going to do is get all products related to that manufacturer
    4. Inside the includes folder I have a functions.js file that will contain all calls to the backend PHP scripts.
    5. I have a Select html object that contains the manufacturer list
    6. I have a DIV tag <div id="divManufacturersProducts"></div> , this DIV will be receiving the new Product select object with the values from SF.
    The calls.

    It all starts with a javascript function call from the HTML:

    HTML Code:
    <select name="cbManufacturer" id="cbManufacturer" style="width: auto; font-size: 12px;" onchange="GetManufacturerProducts();">
      <option selected="selected" value="0">Select Manufacturer</option>
      <option value="Toshiba">Toshiba</option>
      <option value="GE">GE</option>
      <option value="Sony">Sony</option>
      <option value="Nokia">Nokia</option>
      <option value="Motorola">Motorola</option>
    </select>
    Whenever the user changes the manufacturer the select will call GetManufacturerProducts().

    Now inside the includes/functions.js file I have this javascript code:

    Code:
    function GetManufacturerProducts()
    {
        // before anything let the user know the application is working!    
        document.getElementById("divManufacturersProducts").innerHTML = "loading...";
    
        // get the selected manufacturer
        var cbManufacturer = document.getElementById("cbManufacturer")
        var Manufacturer = cbManufacturer.options[cbManufacturer.options.selectedIndex].text;
        
        //----------------------------------------------
        //the first time that we run this code we don’t have a Select html object (cbProducts) to show the products so we need to validate that, if //we have one it means the user changed the manufacturer, so we need to clean all
        var sel = document.getElementById("cbProducts");
        //alert(sel);
        if ( sel != null) {
            var i=0;
            for (i=0;i<=sel.length;i++)
            {
                sel.remove(sel.selectedIndex);
                document.getElementById("divManufacturersProducts").innerHTML = "";
            }
        }
    
        //Personally, I  use one param to have a better control in the business logic 
        var Param = 'manufacturerproducts';    
    
        // This function is what makes the actual call to the backend
        JsHttpRequest.query(
                'classes/Products.BL.class.php', // specify the backend file to call
                {
                    // pass a text value like this: paramname:paramvalue
                                'getManufacturerProducts': Param,  // param to have better control in the BL as you get familiar with it you wont be needing this
                    'Manufacturer': Manufacturer // param to sent the back end the new manufacturer selected by user
                },
                //This Function is called when an answer arrives.             
                function(result, debugMessages) {                
                    document.getElementById("divManufacturersProducts").innerHTML = result.result;    // result.elementname in the BL class result array
                }            
                //false  // do not disable caching.. see library documentation
            );
    }
    So we are calling classes/Product.BL.class.php and we are sending 2 parameters to it, lets see what this BL class has in it:

    PHP Code:
    require_once ('../includes/soapclient/SforcePartnerClient.php'); //put whatever path works for you
        
    require_once ('../includes/soapclient/SforceHeaderOptions.php'); //put whatever path works for you
        
    require_once ('../includes/JsHttpRequest.php'); //put whatever path works for you
        
    require_once ('Products.class.php'); //DAL class …. put whatever path works for you
                       
        
    $result
        
    // Init JsHttpRequest and specify the encoding. It's important!    
        
    $JsHttpRequest =& new JsHttpRequest("iso-8859-1");

        
    // now we read the request looking for the value  of getManufacturerProducts
        
    if ($_REQUEST[getManufacturerProducts] == "manufacturerproducts"
        {
            
    // create the DAL class and ask for the sf values
            
    $P = new clsProducts();       
            
    $result $P->GetManufacturerProductsSelectList($_REQUEST[Manufacturer]);                
        }    

        
    // now, place the result in an array named result ;P
        
    $_RESULT = array(
          
    "result"   => $result 
          
    ); 
    The DAL class

    Here is what i have in the DAL class:

    PHP Code:
    public function GetManufacturerProductsSelectList($Manufacturer)
            {                   
                
    session_start();
                
    $location $_SESSION['location'];
                
    $sessionId $_SESSION['sessionId'];
                
    $wsdl $_SESSION['wsdl'];
                
    $username $_SESSION['usr']; 
                
    $password $_SESSION['pwd']; 
                
    session_write_close();   
            
                
    $client = new SforcePartnerClient();
                
    // this is a trick add '../'to the $wsdl variable otherwise it wont work, at least as i have it ;P
                
    $sforceSoapClient $client->createConnection('../'.$wsdl);
                
    $client->setEndpoint($location);
                
    $client->setSessionHeader($sessionId);
                
    $loginResult $client->login($username$password);
                
                
    $query "Select p.Id, p.Description, p.Family, p.Manufacturer__c, p.Name, p.ProductCode from Product2 p where p.Manufacturer__c = '" $Manufacturer"'";
                
    $queryResult $client->query($query);
                
    $records $queryResult->records;                      
                
                
    // the EVENT on the onchange is to control whatever you need it to run in the javascript, never mind it for now
                
    $selectString "\n\t<select name='cbProducts'  style='width:auto; font-size:12px'  id='cbProducts' onChange='EVENT'>";
                
    $selectString .= "\n\t\t<option value='0' selected >Select Product</option>"
                        
                
    $counter 0;
                foreach (
    $records as $record
                {                
                  
    $sObject = new SObject($record);
                                
                  
    $Id $sObject->Id;
                  
    $Name $sObject->fields->Name;
                  
                  
    $Family $sObject->fields->Family;
                  
    $Image $sObject->fields->Image_URL__c;
                  
    $Manufacturer $sObject->fields->Manufacturer__c;
                  
    $ProductCode $sObject->fields->ProductCode;
                  
    $Description $sObject->fields->Description;
                  
                  
    $selectString .= "\n\t\t<option value='".$Id."'>".$Name."</option>";                    
                  
                  
    $counter++;                 
                }
                
    $selectString .= "\n\t</select>"
                      
                if (
    $counter == 0){
                    
    $selectString "No Products available for " .$Manufacturer ;
                }
                
                        return 
    $selectString;
                
    //return $query;
            

    This should be it, again this code can be optimized, this is a draft but it gives a pretty good idea on how to do this.

    Hope it helps!
    Last edited by lachof; 02-07-2008 at 05:19 PM.
    lachof.

    "So crucify the ego, before it's far too late
    To leave behind this place so negative and blind and cynical,
    And you will come to find that we are all one mind
    Capable of all that's imagined and all conceivable.
    Just let the light touch you
    And let the words spill through
    And let them pass right through
    Bringing out our hope and reason ...
    before we pine away"
    Tool.Lateralus.Reflection

  2. #2
    mike's Avatar
    mike is offline Administrator
    Join Date
    May 2007
    Location
    Wylie, Texas
    Posts
    557
    Blog Entries
    15
    Lachof man Thanks dude, I really appreciate it

    I am going to try this tutorial and see what it does and report back. This is one thing that I need help with

  3. #3
    mike's Avatar
    mike is offline Administrator
    Join Date
    May 2007
    Location
    Wylie, Texas
    Posts
    557
    Blog Entries
    15
    You know one thing that would be nice is to have you include the files that you are referring too and attach them to this thread. I see that you linked it on the JsHttpRequest, but maybe do attach it

    ALSO do you have copies of the actual class's that you are using, you seem to be posting some of the functions/methods that are in your classes

    OR am I wrong, if so, sorry.....

  4. #4
    lachof is offline Junior Member
    Join Date
    Nov 2007
    Posts
    10

    Files

    Not wrong at all , here are all the files involved

    You can find more info and downloads about the ajax libraries used here

    Saludos!

    lachof
    Attached Files

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

SEO by vBSEO 3.5.1