P
P
pegas2019-10-21 22:24:31
MODX
pegas, 2019-10-21 22:24:31

How to send an ajax request in modx using a component?

I'm sending an ajax request, to a resource named ajax :

$.ajax({
               type: "POST",
               url: '/ajax',
               data: {
                    action: 'getProductPopup',
                    data: {id: id}
                },
               success: function(data) {
                    $('.content__wrapper').html(data);
               }
         });

In this resource, I call a snippet with the following code:
<?php
$action = $_POST['action'];
$data = $_POST['data'];

if (!function_exists('ajaxResponse')) {
    function ajaxResponse($success, $data, $msg) {
        return json_encode(['success' => $success, 'data' => $data, 'msg' => $msg]);
    }
}

switch($action) {
    case 'getProductPopup':
        if (!array_key_exists('id', $data)) {
            ajaxResponse();
        }
        
        $pdoTools = $modx->getService('pdoTools');
        
        $id = intval($data['id']);
        
        // msProduct наследник modResource
        $obj = $modx->getObject('msProduct', $id);
        
        if (!$obj) {
            ajaxResponse();
        }
        
        return $pdoTools->getChunk('popupProduct', $obj->toArray());
    break;
    default:
        return false;
    break;
}

return false;

How can I do the same thing, only in the public_files/components/ajaxService/index.php file ?
I tried to copy the snippet code into this file and specify the path public_files/components/ajaxService/index.php in Ajax, but it gives an error 500

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-10-22
@1PeGaS

Did you include $modx in your public_files/components/ajaxService/index.php file? After all, it is used in the snippet.

// Подключаем
define('MODX_API_MODE', true);
require $_SERVER['DOCUMENT_ROOT'].'/index.php';
 
// Включаем обработку ошибок
$modx->getService('error','error.modError');
$modx->setLogLevel(modX::LOG_LEVEL_INFO);
$modx->setLogTarget(XPDO_CLI_MODE ? 'ECHO' : 'HTML');
 
//Проверяем работу:
if ($res = $modx->getObject('modResource', 1)) {
    print_r($res->toArray());
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question