Search code examples
javascriptphpajaxhookwhmcs

How to use ajax for request the WHMCS hooks function and get my required return data?


I read the WHMCS demo code for developing a provisioning module:

the frontend code, overview.tpl.

the backend code, provisioningmodule.php.

but my code follow by the upper I want to use ajax for request, so the whole page will not re-render.


My frontend ajax code:

    jQuery.ajax({
        url: url,
        type: "POST",
        data: {
            ...
            qn_action: "bmc"

        },
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus){

            console.log('ldl:',data)  // pay attention I want to console.log the return data. I wish it be the PHP return data's `templateVariables`.
            jQuery('.powercontrol').removeClass('disabled');
            jQuery(i_id).css('display', 'none');

            jQuery('#powerstatus-spinner').css('display', 'none'); // Status loading
        },
        error: function(jqXHR, e) {
            var msg = '';
            if(jqXHR.status==0){
                msg = 'You are offline!!\n Please Check Your Network.';
            }else if(jqXHR.status==404){
                msg = 'Requested URL not found.';
            }else if(jqXHR.status==500){
                msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
            }else if(e=='parsererror'){
                msg = 'Error: Parsing JSON Request failed.';
            }else if(e=='timeout'){
                msg = 'Request Time out.';
            }else {
                msg = 'Unknow Error.<br/>'+x.responseText;
            }

            console.log('error: '+jqXHR.responseText);  // I wil get the error logs
            console.log('Error msg: '+msg);
        }
    })

in my backend PHP code:

function qidicatedserver_ClientArea(array $params)
{

    // Determine the requested action and set service call parameters based on
    // the action.

    $qn_action = isset($_REQUEST['qn_action']) ? $_REQUEST['qn_action'] : '';

    $tblclients_id = isset($_REQUEST['tblclients_id']) ? $_REQUEST['tblclients_id'] : '';  


    $bmc_action = "";
    $server_name = "";
    $templateFile = 'templates/overview.tpl';
    $bmc_result = "";


    if($qn_action == "bmc"){

        $resp = array(
            'tabOverviewReplacementTemplate' => $templateFile,
            'templateVariables' => array(
                "status"=>200,
                "data"=>"my test return data"
            )
        );



        return $resp;


    }


    try {
        // Call the service's function based on the request action, using the
        // values provided by WHMCS in `$params`.


        return array(
            'tabOverviewReplacementTemplate' => $templateFile,
            'templateVariables' => array(
                'data' => array(
                    "status"=>"200",
                    "data" => array(
                        "bmc_result" => null
                    )
                ),
            ),
        );


    } catch (Exception $e) {

        //echo $e;
        // Record the error in WHMCS's module log.
        logModuleCall(
            'qidedicatedserver',
            __FUNCTION__,
            $params,
            $e->getMessage(),
            $e->getTraceAsString()
        );
        // In an error condition, display an error page.
        return array(
            'tabOverviewReplacementTemplate' => 'templates/error.tpl',
            'templateVariables' => array(
                'usefulErrorHelper' => $e->getMessage(),
            ),
        );

    }

}

when the ajax request executed, there will get error, execute the below code:

console.log('error: '+jqXHR.responseText);  // I wil get the console log: `error: <!DOCTYPE html> \n<html lang="en">\n<head>\n    <meta char) ....` the html is the whole page's HTML
console.log('Error msg: '+msg);  // the console log: `Error msg: Error: Parsing JSON Request failed.`

So, there must be issue in there, my problem is how to use ajax for HTTP request in WHMCS custom provisioning module, but I try get failed like upper. (I tried use form request PHP, there can get correct data, but there will re-fresh the whole page, its not my desired, I don't what the page to be refresh)

Who can tell me how to use ajax for request WHMCS hook function and return correct data as my wish?


You can find more introduction of WHMCS provisioningmodulethere.


EDIT-01

I tried change the return PHP code like this:

if($qn_action == "bmc"){

    $resp = array(
        'tabOverviewReplacementTemplate' => $templateFile,
        'templateVariables' => json_encode(array(
            "status"=>200,
            "data"=>"dasdas"
        ))
    );



    return $resp;


}

but still this error.


Solution

  • Put your Ajax/PHP code in separated file, not in _ClientArea method, suppose your module called 'mail_service', then create a file in:

    \modules\servers\mail_service\for_json.php

    for_json.php

    <?php
    #define("ADMINAREA", true);
    define("CLIENTAREA", true);
    #define("SHOPPING_CART", true);
    require_once(__DIR__ . '/../../../init.php');
    require_once(ROOTDIR . '/includes/dbfunctions.php');
    #require(ROOTDIR . "/includes/orderfunctions.php");
    #require(ROOTDIR . "/includes/domainfunctions.php");
    #require(ROOTDIR . "/includes/configoptionsfunctions.php");
    #require(ROOTDIR . "/includes/customfieldfunctions.php");
    #require(ROOTDIR . "/includes/clientfunctions.php");
    #require(ROOTDIR . "/includes/invoicefunctions.php");
    #require(ROOTDIR . "/includes/processinvoices.php");
    #require(ROOTDIR . "/includes/gatewayfunctions.php");
    #require(ROOTDIR . "/includes/modulefunctions.php");
    #require(ROOTDIR . "/includes/ccfunctions.php");
    #require(ROOTDIR . "/includes/cartfunctions.php");
    #include_once(ROOTDIR . '/includes/clientareafunctions.php');
    
    #use WHMCS\ClientArea;
    #use WHMCS\Database\Capsule;
    #use WHMCS\Smarty ;
    file_put_contents("C:/xampp_my/htdocs/my/sss.txt",var_export($_POST,true));
    if(isset($_POST['qn_action']) && $_POST['qn_action']=="bmc")
    {
        // do your job
        //header('Content-type: application/json; charset=utf-8');
        header("Content-Type: application/json", true);
    
        header('HTTP/1.0 200 OK');
        echo '{"menu": {"id": "file","value": "File","popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}';
    }
    ?>
    

    and use the follwing JS code:

    jQuery.ajax({
        url: "/modules/servers/mail_service/for_json.php",
        type: 'POST',
        data: {qn_action: 'bmc'},
        cache: false,
        dataType: 'json',
        success: function (data, textStatus){console.log('ldl:',data)},
        error: function(jqXHR, e){
            var msg = '';
            if(jqXHR.status==0){
                msg = 'You are offline!!\n Please Check Your Network.';
            }else if(jqXHR.status==404){
                msg = 'Requested URL not found.';
            }else if(jqXHR.status==500){
                msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
            }else if(e=='parsererror'){
                msg = 'Error: Parsing JSON Request failed.';
            }else if(e=='timeout'){
                msg = 'Request Time out.';
            }else {
                msg = 'Unknow Error.<br/>'+x.responseText;
            }
            console.log('error: '+jqXHR.responseText);  // I wil get the error logs
            console.log('Error msg: '+msg);
        }
    })