0

Please, explain to me how to run snippet CookieList with ajax?

I tried next:
1. Created snippet ajaxCookieList:

<?php
if (isset($_POST["action"])) {
    $values = $modx->runSnippet('addToCookieLIst',array(
        'value' => $_POST['action']
    ));
    $output = $modx->runSnippet('pdoResources',[
            'parents' => 6,
            'resources' => $values,
            'tpl' => 'popup.favorites.item',
            'includeTVs' => 'header.bgImage,franchise.logo,franchise.price,title,subtitle',
            'prepareTVs' => '1',
            'hideContainers' => '1'
        ]);
    return $output; 
}
  1. Then i created chunk with this code:

    <script> jQuery(function($){ $('a.franchise-pin, a.franchise-favorite-add').click(function(e){ var value = $(this).data('value'); $.post(document.location.href, {action: value}, function(data) { $('#favorites').html(data); $('#favorites').modal('show'); }); e.preventDefault(); }); }); </script>

But response is all page..

What is wrong?

2 Answers2

0

What I usually do in such cases:

  1. I place a snippet call ([[!ajaxCookieList]]) on a service page accessible via URL like /page-with-snippet/
  2. In JS (ajax) I use that URL to which I send parameters
  3. The snippet has to get the parameters I send. So, I really call it like this: [[!ajaxCookieList? &action=[[!#POST.action]]]]
  4. Access to parameters in snippets is possible like this: $option = $modx->getOption('action', $scriptProperties, 'default_value', true);
  5. I do my stuff in the snippet

But in your case, I think, everything can be simpler. You use one of the pdoTools snippets and if I am not mistaken, you can just place pdoResources snippet call on a page (/page-with-snippet/) like this:

[[pdoResources?
  &parents=`6`
  &resources=`[[!addToCookieLIst? &value=`[[!#POST.action]]` ]]` // your snippet should return comma-separated list of resources` ids that you pass then to pdoResources
  &tpl=`popup.favorites.item`
  &includeTVs=`header.bgImage,franchise.logo,franchise.price,title,subtitle`
  &prepareTVs=`1`
  &hideContainers=`1`
]] 

and now you can send parameters to this page (/page-with-snippet/) via AJAX and get the results if there are any. I hope I didn't mess anything - you had better check it again, but you get the idea at least :) BTW, check this article on modx.com that teaches how to write a good snippet.

Also another minor issue: as it has been pointed out here, the use of window.location is preferable to document.location.

curveball
  • 4,320
  • 15
  • 39
  • 49
0

Here is another solution I did. I used pdoResources. Hope that you will understand my code and customize it for yourselves.

  1. Create snippet ajaxCookieList

  2. Paste JS-code in your custom.js file

  3. Simple markup for resources. Insert it in the chunk:

<a href="#" data-id=[[+id]] data-action="add">Add to wish list</a>

<a href="#" data-id=[[+id]] data-action="remove">Remove from wish list</a>

Thas all:)