We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 43985
    • 5 Posts
    When I execute a snippet that searches into the DB through javascript like that:
     <script>
       $('select').on('change', function() {
       $snippet = "[!ProductList? &cid=`1`!]";
       $("#productlist").html($snippet);
       });
       </script>

    it works fine and returns the record found.
    But when I try to execute it passing a variable as the snippet's parameter I get no results:
    <script>
       $('select').on('change', function() {
       alert("Category Id value:**" +  this.value + "**");
       $snippet = "[!ProductList? &cid=`" + this.value + "`!]";
       $("#productlist").html($snippet);
       });
       </script>

    This will not work...
    The snippet:
    <?php
    if (isset($cid)) {
       $res = $modx->db->select("*", "learningmodx.products", "categoryid='" . $cid . "'" );
    } else {
       $res = $modx->db->select("*", "learningmodx.products");
    }
    
    $products= $modx->db->makeArray($res); // Convert the recordset to an array
    
    $o='';
    foreach ($products as $product) {
       $o .= "<div class='listitem'>";
       $o .= "<img src='" . $product["photopath"] . "' class='productimage' />";
       $o .= $product["name"];
       $o .= "<br>";
       $o .= $product["description"];
       $o .= "<br>";  
       $o .= "</div>";
    }
    
    return $o;
    ?>

    I did not find a post answering this. I suspect I'm doing something fundamentally wrong. I am using EVO 1.0.10.
      • 9207 ☆ A M B ☆
      • 2,475 Posts
      Is that valid Javascript? It looks like you're mixing Javascript in PHP in ways that I'm not sure are valid, specifically this bit:

      $snippet = "[!ProductList? &cid=`" + this.value + "`!]";


      I would expect that to be Javascript (not PHP), something like this:

      var snippet = "[!ProductList? &cid=`" + this.value + "`!]";


      But even that won't work because you're trying to pass a Javascript value to PHP -- the train has already left the station. PHP will execute and be done before the content is sent to the browser and long before Javascript will run. So you can't pass a JS variable to a snippet like that. The only thing you could do is set up an Ajax request to post JS data to a PHP handler page.

      Hope that helps.
        • 4172
        • 5,888 Posts
        you are trying to run a snippet with a value from javascript?

        this can not work.
        snippets are running serverside, long before you are running your javascript clientside.

        you will need to place your snippet on an own resource with an emtpy template and call that resource by ajax to get the snippet-result as response.
          -------------------------------

          you can buy me a beer, if you like MIGX

          http://webcmsolutions.de/migx.html

          Thanks!
          • 43985
          • 5 Posts
          Thank you very much for your replies both.

          you will need to place your snippet on an own resource with an emtpy template and call that resource by ajax to get the snippet-result as response.
          Any available tutorials on how to do this?

          I thought it could work because each time the javascript code was called the php code was also called and receiving a different $cid. I got very confused on this.
            • 9207 ☆ A M B ☆
            • 2,475 Posts
            You're jumping into the deep-end a little bit here -- this is more of a general web-dev question than it is a MODX question. You need to get your Javascript working independently and your PHP working independently before you try to bring them together. My advice is to stick to one or the other: if you're going to learn some PHP dev, then start with that and don't try to tie Javascript into it yet.

            Re tutorials: again, I would avoid jumping into Ajax until you're really solid on your other dev skills. There are a lot of moving parts with a page, and Ajax makes everything *much* more complicated, and debugging it can be very very difficult and frustrating. It's a high price to pay for some eye-candy. Everything that can be done with Ajax can be done without Ajax (you just need more mouse-clicks and page reloads). If you want to start learning it, I would work through some of the jQuery Ajax tutorials.
              • 43985
              • 5 Posts
              What I want to achieve is having a products list that gets updated when the user selects a product category from a select field.
              I had test the snippet and the javascript part independently and they seemed to work alright... By the way I changed the js code according to your suggestions.
              Is there any other way to achieve my goal without messing with Ajax? I have no intention to complicate matters, unless I absolutely have to.
                • 9207 ☆ A M B ☆
                • 2,475 Posts
                If you want to do this without JS, you would generally use a form that submits with a variable for the category. It's always important to sanitize your inputs -- in your case this should be easy because you'd be passing an id (presumably an integer). Consider something like this in your HTML:

                <form action="" method="get">
                    <option name="cid">
                        <select value="1">Category 1</select>
                        <select value="2">Category 2</select>
                        ... etc ...
                    </option>
                    <input type="submit">Refresh</input>
                </form>


                Note that the "name" parameter is "cid", and in this example I used "get" -- you might prefer to use "post". Change $_GET and $_POST accordingly.

                Then make your Snippet listen for the "cid" parameter:

                $cid = null; // initialize
                if (isset($_GET)) { 
                    $cid = (int) $_GET['cid'];
                }
                if ($cid) {
                   $res = $modx->db->select("*", "learningmodx.products", "categoryid='" . $cid . "'" );
                } else {
                   $res = $modx->db->select("*", "learningmodx.products");
                }
                // ... etc...


                It's not as user-friendly because the page has to reload each time a new category is selected, but it should be much easier to code and debug.

                Once you have that working, you could do the Ajax bit: make a separate MODX page that uses no template (i.e. blank). To test, paste in some static HTML -- maybe just start with "Hello world", but eventually you'll want to use HTML representing the output that your Snippet would normally kick out. Make a copy of your original page, and set it up so that it uses an Ajax request to that other MODX page. It's sorta like doing a "javascript include": it should send an Ajax request to the other page, then write it back to the original page. This is where those JQuery tutorials would come in. Once you have the Ajax working, then you can go back to the separate "Hello World" page and replace it with your Snippet to make it dynamically print out the HTML you require.

                Hope that helps.
                  • 4172
                  • 5,888 Posts
                  you could also use direct links together with Everett's snippet:

                  <ul>
                  <li><a href="[~[*id*]~]?cid=1">Category 1</a></li>
                  <li><a href="[~[*id*]~]?cid=2">Category 2</a></li>
                  <li><a href="[~[*id*]~]?cid=3">Category 3</a></li>
                  </ul>



                    -------------------------------

                    you can buy me a beer, if you like MIGX

                    http://webcmsolutions.de/migx.html

                    Thanks!
                    • 43985
                    • 5 Posts
                    I did it with POST as you suggested. I will keep it this way unless the user wants improvements...

                    Thank you very much both, you 've been extremely helpful.