Ajax, REST API OpenCart

In this article, we will look at how ajax requests are arranged  in OpenCart , including requests through the  OpenCart api , we will get acquainted with the new concept of  front controller  and touch on the topic of ajax REST API a little  .





Customer

The OpenCart client side works using  jquery , which means it can be used  $.ajax



 from this library. Link to documentation . Examples of ajax requests on the client side can be found in  admin/view/template/sale/order_form.tpl



 (.twig for OpenCart 3.0).





Server

Looking at the same file  admin/view/template/sale/order_form.tpl



 (for OpenCart 2.3), you can understand that the  classic OpenCart routing scheme is used as the call address . Let's look at one of the requests:





$.ajax({
    url: 'index.php?route=customer/customer/autocomplete&token=<?php echo $token; ?>&filter_name=' +  encodeURIComponent(request),
    ...
      
      



It's simple:  url is the path to the controller and, if necessary, the  name of the method of this controller .





That is, we need  to create a controller class , then from the view files we can  call methods of this controller with  ajax requests .





 admin/controller/extension/module/myajax.php:







class ControllerExtensionModuleMyAjax extends Controller
{
    public function index()
    {
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode(
            [
                "success" => true, 
                "message" => "ok", 
                "data" => []
            ]
        ));
    }
}
      
      



 response



,  Response



 ,  system/library/response.php



. . 2 :





  • addHeader($header)



     - http , header



     





  • setOutput($output)



     - , output



     





 -





$this->response





OpenCart 2  / (admin, catalog), :





  • admin



     -  get



      ( ):





    • OpenCart 2.3 token



      ,  $this->session->data['token']







    • OpenCart 3.0 ¨C4C, ¨C14C¨C5C





  • catalog



     - ,





 ajax    ( html)  js ( OpenCart 2.3):





$.ajax({
    url: '<?php echo $admin; ?>index.php?route=extesion/module/myajax&token=<?php echo $token; ?>',
    type: 'get',
    dataType: 'json',
    success: function(json) {
        alert("success: "+json["success"]+"\n"+"message: "+json["message"]);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
    }
});
      
      



url admin



   (admin catalog). 2 ,  admin/config



:





  • HTTP_SERVER



      HTTP<b style="box-sizing: border-box;">S</b>_SERVER



     -  admin



     ( - ),





  • HTTP_CATALOG



      ¨C6C¨C15C- , ¨C16C¨C7C





Ajax API

 admin/view/template/sale/order_form.tpl



 (OpenCart 2.3), ajax  catalog



 , .





 token



, ajax  /index.php?route=api/login



, json ,  token



:





var token = '';
 
// Login to the API
$.ajax({
    url: '<?php echo $catalog; ?>index.php?route=api/login',
    type: 'post',
    data: 'key=<?php echo $api_key; ?>',
    dataType: 'json',
    crossDomain: true,
    success: function(json) {
    //...
 
        if (json['token']) {
            token = json['token'];
        }
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
    }
});
      
      



 catalog/controller/api/login.php ControllerApiLogin::index



. :









  • (catalog/model/account/api.php - ModelAccountApi::addApiSession



    )





  •  ( token



       system/helper/general.php



    ),





json ajax , api (api_key



)   (--API).





 admin/view/template/sale/order_form.tpl



  ,  ajax ,  route=api/...



   token



,  ( api , )¨C25C :





if (!isset($this->session->data['api_id'])) {
    $json['error']['warning'] = $this->language->get('error_permission');
} else {
    ...
}
      
      



Ajax  catalog



   token



 





, ,  ajax   .





 index.php



   system/startup.php



,  system/framework.php



  :





// Front Controller
$controller = new Front($registry);
 
// Pre Actions
if ($config->has('action_pre_action')) {
    foreach ($config->get('action_pre_action') as $value) {
        $controller->addPreAction(new Action($value));
    }
}
      
      



 front controller,  system/engine/front.php



 Front



.





:)





,  front controller  / ,    startup/router



   controller



  (admin/controller



  catalog/controller



),   ,   $_['action_pre_action'];



   system/config/catalog.php



.





 front controller, ,  dispatch



 ( action  $config->get('action_router')



):





// Dispatch
$controller->dispatch(new Action($config->get('action_router')), new Action($config->get('action_error')));
      
      



 startup/session



  catalog/controller



,  ControllerStartupSession::index



    api . :





  •  api/



       get



      token







  • api





  • api ip





  • id  $_COOKIE["api"]







  • , ( , )





, , $this->session->data['api_id']



  , ip .





Ajax REST API

REST API OpenCart.





 ajax OpenCart  admin



  catalog



 .





 admin



,  admin



 . , .  ( )   catalog



  ( ), .  catalog



     ( ).





 REST API OpenCart  :





  •  $this->response



    ,  addHeader



      setOutput



     





  •  catalog



    ¨C22C





  • api ¨C24C¨C10C¨C25C , ¨C26C¨C11C¨C27C, ajax





    catalog/controller/api/



,   ajax   , ajax  api/login



. ajax , , ,  admin/view/template/sale/order_form.tpl.



REST API , , :





  • https://ru.wikipedia.org/wiki/REST





  • https://habr.com/ru/post/483202/









Author: Vitaly Buturlin












All Articles