Search code examples
phpibm-mobilefirstworklight-adapters

IBM Worklight - How to access JSON sent using an adapter in server-side PHP?


I am developing a hybrid application in IBM Worklight.

In my app, there is a registration form. I have a requirement: After the user registers with the app, the form data will be sent to an external server in JSON format using an HTTP adapter.

In the external server,

  • How to access the JSON data sent using the HTTP adapter in a PHP file? and
  • How to send back a response in the same JSON format?

Please give demo codes of both HTTP adapter and server side PHP code.


Solution

  • Client code:

    function callAdapter(){
    
        var invocationData = {
                adapter : 'MyAdapter',
                procedure : 'MyAdapterProcedure',
                parameters : [username, password]
        };
    
        WL.Client.invokeProcedure(invocationData, {
            onSuccess : adapterSuccessCallback,
            onFailure : adapterFailureCallback
        });
    }
    

    Adapter implementation:

    function myAdapterProcedure(username, password) {
    
        var credentials = JSON.stringify({username: username, password: password});
    
        var input = {
            method : 'post',
            returnedContentType : 'json',
            path : "/myPHPscript.php",
            parameters: {credentials: credentials}
        };
    
    
        return WL.Server.invokeHttp(input);
    }
    

    PHP script:

    <?php
            $jsonObj = $_POST['credentials'];
            $credentials = json_decode($jsonObj)
    
            // sanitation, database calls, etc
    
            $returnDict = array();
            $returnDict["success"] = true;
            echo json_encode($returnDict);
    ?>