Page 1 of 2 12 LastLast
Results 1 to 10 of 18
  1. #1

    bug Using XHR Request for Ajax based on what product(s) are chosen

    Sorry if this is in the wrong forum – essentially the problem I have has to do with appearance changing aspects, though there are function changes as well.

    I have a function that is using
    Code:
    $("#divID").load(ajax.php...)
    to execute a change in the page based on which product the user clicked to initiate the function. The buttons related to this function for each product have
    HTML Code:
    onclick="javascript: loadFunction(...)
    So when one is clicked it calls the function with parameters unique to the product and what the button should do to the page.

    When the request for "ajax.php" is sent (the file is in site root httpdocs/) it returns page_not_found.html because of this line in "init_sanitize.php":

    Code:
    if ((! isset ( $_SESSION ['securityToken'] ) || ! isset ( $_POST ['securityToken'] )) || ($_SESSION ['securityToken'] !== $_POST ['securityToken']))
          {
            zen_redirect ( zen_href_link ( FILENAME_PAGE_NOT_FOUND, '', $request_type ) );
          }
    If I comment out
    Code:
    zen_redirect ( zen_href_link ( FILENAME_PAGE_NOT_FOUND, '', $request_type ) );
    then the load is successful and everything happens correctly. How can I make it so that the "ajax.php" file is allowed to .load() through this 'securityToken' statement?

    Thanks!

    ---

    P.S. I am working from a comparison module found here that I have modified the functionality and structure of for my own site. This particular issue was brought up in the support thread with the same pseudo-solution I found (commenting the redirect out) but like the module author, I think this is too drastic a measure to take. So I'm just wondering how to get the file that it's trying to load to pass 'securityToken' instead of just not allowing any redirects at all.

  2. #2
    Join Date
    Jan 2004
    Posts
    66,373
    Blog Entries
    7
    Plugin Contributions
    274

    Default Re: Using XHR Request for Ajax based on what product(s) are chosen

    When POSTing data to Zen Cart, there is CSRF protection built-in, which requires that you pass the valid securityToken with the POST data.

    What EXACTLY are you POSTing? (complete request details, please)
    .

    Zen Cart - putting the dream of business ownership within reach of anyone!
    Donate to: DrByte directly or to the Zen Cart team as a whole

    Remember: Any code suggestions you see here are merely suggestions. You assume full responsibility for your use of any such suggestions, including any impact ANY alterations you make to your site may have on your PCI compliance.
    Furthermore, any advice you see here about PCI matters is merely an opinion, and should not be relied upon as "official". Official PCI information should be obtained from the PCI Security Council directly or from one of their authorized Assessors.

  3. #3

    Default Re: Using XHR Request for Ajax based on what product(s) are chosen

    Sorry to double post but when I tried to use "Edit Post" the edit screen had an empty box where the existing source for the post should be

    Just after posting I noticed something about the request when it works/doesn't work. When it works (meaning when I comment out the zen_redirect line) the Request Method for the file is 'POST' and it gets a 200 'OK' Status Code. When I leave the zen_redirect in and it doesn't work (returning page_not_found.html) the Request Method is 'GET' and the Status is 404 not found.

    The entire if(){} in init.sanitize.php is:
    PHP Code:
      if ((isset ( $_GET ['action'] ) || isset($_POST['action']) ) && $_SERVER['REQUEST_METHOD'] == 'POST')
      {
        
    $mainPage = isset($_GET['main_page']) ? $_GET['main_page'] : FILENAME_DEFAULT;
        if (!
    in_array($mainPage$csrfBlackList))
        {
          if ((! isset ( 
    $_SESSION ['securityToken'] ) || ! isset ( $_POST ['securityToken'] )) || ($_SESSION ['securityToken'] !== $_POST ['securityToken']))
          {
            
    zen_redirect zen_href_link FILENAME_PAGE_NOT_FOUND''$request_type ) );
          }
        }
      } 
    so even though it redirects due to the last if statement, maybe it has more to do with the first one referring to request methods?

  4. #4

    Default Re: Using XHR Request for Ajax based on what product(s) are chosen

    Quote Originally Posted by DrByte View Post
    When POSTing data to Zen Cart, there is CSRF protection built-in, which requires that you pass the valid securityToken with the POST data.

    What EXACTLY are you POSTing? (complete request details, please)
    Request Header Source with zen_redirect left in:
    Code:
    GET /page_not_found.html HTTP/1.1
    Host: localhost
    Connection: keep-alive
    Accept: text/html, */*; q=0.01
    X-Requested-With: XMLHttpRequest
    User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
    Referer: http://localhost/tfts-capacitive-touch-tfts-c-1_958.html
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8
    Cookie: zenid=8e737pk1ltqmq7u0rmdeeo4co7; __utmt=1; __utma=111872281.2082644287.1454086597.1454345510.1454429888.7; __utmb=111872281.43.10.1454429888; __utmc=111872281; __utmz=111872281.1454086597.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
    Request Header Source with zen_redirect commented out:
    Code:
    POST /ajax_compare.php HTTP/1.1
    Host: localhost
    Connection: keep-alive
    Content-Length: 26
    Accept: text/html, */*; q=0.01
    Origin: http://localhost
    X-Requested-With: XMLHttpRequest
    User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
    Content-Type: application/x-www-form-urlencoded; charset=UTF-8
    Referer: http://localhost/tfts-capacitive-touch-tfts-c-1_958.html
    Accept-Encoding: gzip, deflate
    Accept-Language: en-US,en;q=0.8
    Cookie: zenid=8e737pk1ltqmq7u0rmdeeo4co7; __utmt=1; __utma=111872281.2082644287.1454086597.1454345510.1454429888.7; __utmb=111872281.44.10.1454429888; __utmc=111872281; __utmz=111872281.1454086597.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)

  5. #5
    Join Date
    Jan 2004
    Posts
    66,373
    Blog Entries
    7
    Plugin Contributions
    274

    Default Re: Using XHR Request for Ajax based on what product(s) are chosen

    You didn't show what data you're POSTing ... just the headers.

    Maybe it's better if you post your complete HTML of the page, and all the jQuery code also being loaded in the page.

    A lot more detail is needed. You're obfuscating too much stuff when posting here, which prevents us helping you. Happy to help, but specifics are needed.
    .

    Zen Cart - putting the dream of business ownership within reach of anyone!
    Donate to: DrByte directly or to the Zen Cart team as a whole

    Remember: Any code suggestions you see here are merely suggestions. You assume full responsibility for your use of any such suggestions, including any impact ANY alterations you make to your site may have on your PCI compliance.
    Furthermore, any advice you see here about PCI matters is merely an opinion, and should not be relied upon as "official". Official PCI information should be obtained from the PCI Security Council directly or from one of their authorized Assessors.

  6. #6

    Default Re: Using XHR Request for Ajax based on what product(s) are chosen

    Quote Originally Posted by DrByte View Post
    You didn't show what data you're POSTing ... just the headers.

    Maybe it's better if you post your complete HTML of the page, and all the jQuery code also being loaded in the page.
    I was going to post the full HTML rendered from Chrome Inspector Tool but I didn't know how to control the size of the "[HTML]" Tag box and it was rather large as-is.

    The contents of ajax_compare.php:
    PHP Code:
    <?php
    /**
     * ajax_compare.php
     * ajax call to show products selected for comparison
     *
     * @package general
     * @copyright Copyright 2003-2010 Zen Cart Development Team
     * @copyright Portions Copyright 2003 osCommerce
     * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
     * @version $Id: ajax_compare.php 00001 2011-01-28 5:23:52MT brit (docreativedesign.com) $
     */

    require('includes/application_top.php');
    include(
    DIR_WS_LANGUAGES $_SESSION['language'].'/'.FILENAME_DEFINE_COMPARE_LANGUAGE);

    // get values
    $action $_POST['action'];
    $selected $_POST['compare_id'];
    $compare_array = array();
    $comp_images '';
    $compare_warning '';

    $comp_value_count count($_SESSION['compare']);

    // add new products selected
    if ($action == 'add') {
        if (
    $comp_value_count COMPARE_VALUE_COUNT) {
            
    $compare_array[] = $selected;
            foreach (
    $_SESSION['compare'] as $c) {
                if (
    $c != $selected) {
                    
    $compare_array[] = $c;
                }
            }
            
    $_SESSION['compare'] = array_unique($compare_array);
        } else {
            
    $compare_warning '<div id="compareWarning">' COMPARE_WARNING_START COMPARE_VALUE_COUNT COMPARE_WARNING_END '</div>';
        }


    // remove products
    if ($action == 'remove') {
        foreach (
    $_SESSION['compare'] as $rValue) {
            if (
    $rValue != $selected) {
                
    $removed_compare_array[] = $rValue;
            }
            
    $_SESSION['compare'] = array_unique($removed_compare_array);
        }
    }

    // return new value for the session
    foreach ($_SESSION['compare'] as $value) {
        if (!empty(
    $value)) {
            
    $product_comp_image $db->Execute(
                
    "SELECT p.products_id, p.master_categories_id, pd.products_name, p.products_image
                 FROM " 
    TABLE_PRODUCTS " p
                 LEFT JOIN " 
    TABLE_PRODUCTS_DESCRIPTION " pd
                 ON pd.products_id=p.products_id
                 WHERE p.products_id='"
    .$value."'"
            
    );
            
    $comp_images .= '<div class="compareAdded"><a href="' zen_href_link(zen_get_info_page($product_comp_image->fields['products_id']), 'cPath=' . (zen_get_generated_category_path_rev($product_comp_image->fields['master_categories_id'])) . '&products_id=' $product_comp_image->fields['products_id']) . '">' zen_image(DIR_WS_IMAGES $product_comp_image->fields['products_image'], $product_comp_image->fields['products_name'], '''35''class="listingProductImage"') . '</a><div>'.'<a name="rmv'.$product_comp_image->fields['products_id'].'" onclick="javascript: compareNew('.$product_comp_image->fields['products_id'].', \'remove\')" alt="remove">'.COMPARE_REMOVE.'</a>'.'</div></div>';
        }
    }

    // return HTML view of found products
    if (!empty($comp_images)) {
        echo 
    '<div id="compareMainWrapper"><div class="compareAdded compareButton">'.'<a href="index.php?main_page=compare" alt="compare">'.'<span class="cssButton">'.COMPARE_BUTTON_DEFAULT.'</span></a></div>'.$comp_images.'</div>';
    } else { echo 
    '<script type="text/javascript">' 'hideCompare();' '</script>'; }
    echo 
    '<br class="clearBoth" />';

    // send back warning if more than allowed is selected
    echo $compare_warning;

    require(
    'includes/application_bottom.php');
    ?>

    The jQuery containing the .load(ajax_compare.php...):
    Code:
    $(document).ready(function(){ 
        $('#compareResult:not(:has(.compareAdded))').css("display", "none");
        for (index = 0; index < data.length; index++) {
            $("input[name='" + data[index] + "']").prop("checked",true);
        }
    });
    
    function compareNew(obj, action) {
        $('#compareResult').show();
        if ( $("input[name='" + obj + "']").is(":checked") && $("a[name='rmv" + obj + "']").length ) {
            if ( action == 'remove' ) {
            $("input[name='" + obj + "']").prop("checked",false);
            } else if ( action == 'add' ) { }
        }
        else if ( $("input[name='" + obj + "']").is(":checked") && $("a[name='rmv" + obj + "']").length === 0 ) { }
        else {
            action = 'remove';
        }
        $('#compareProducts').load('ajax_compare.php', {'compare_id': obj, 'action': action});
        
    }
    
    
    
      function hideCompare() {
          $('#compareResult').hide();
      }

  7. #7
    Join Date
    Jan 2004
    Posts
    66,373
    Blog Entries
    7
    Plugin Contributions
    274

    Default Re: Using XHR Request for Ajax based on what product(s) are chosen

    Changing your load() line to something like this would probably do it:

    Code:
    $('#compareProducts').load('ajax_compare.php', {'compare_id': obj, 'action': action, 'securityToken': '<?php echo $_SESSION['securityToken']; ?>'});
    BUT then you'd have to also rename the jscript_products_compare.js to jscript_products_compare.php instead (and add the <script> header and </script> footer to the file contents), so that the PHP code can properly echo out the token.
    Last edited by DrByte; 3 Feb 2016 at 03:48 AM. Reason: added missing quotes
    .

    Zen Cart - putting the dream of business ownership within reach of anyone!
    Donate to: DrByte directly or to the Zen Cart team as a whole

    Remember: Any code suggestions you see here are merely suggestions. You assume full responsibility for your use of any such suggestions, including any impact ANY alterations you make to your site may have on your PCI compliance.
    Furthermore, any advice you see here about PCI matters is merely an opinion, and should not be relied upon as "official". Official PCI information should be obtained from the PCI Security Council directly or from one of their authorized Assessors.

  8. #8

    Default Re: Using XHR Request for Ajax based on what product(s) are chosen

    Quote Originally Posted by DrByte View Post
    Changing your load() line to something like this would probably do it:

    Code:
    $('#compareProducts').load('ajax_compare.php', {'compare_id': obj, 'action': action, 'securityToken': <?php echo $_SESSION['securityToken']; ?>});
    BUT then you'd have to also rename the jscript_products_compare.js to jscript_products_compare.php instead (and add the <script> header and </script> footer to the file contents), so that the PHP code can properly echo out the token.
    I changed the .load() line to what you suggested and added "<script type="text/javascript"> ... </script>" header and footer. Then I renamed it as .php. When trying the page again after this the console gives an Uncaught Syntax Error: Unexpected identifier on line 50 in the page <head>. The error line is this:
    Code:
    $('#compareProducts').load('ajax_compare.php', {'compare_id': obj, 'action': action, 'securityToken': 32211a3feaf03d8d7608ccbb28f392c2});
    It points to the "a3feaf03d8d7608ccbb28f392c2" as the Unexpected Identifier. Clicking the button that calls compareNew() gives an error that says compareNew is not defined.

    The whole <head> for the page is now:
    HTML Code:
    <head>
    <title>Capacitive Touch TFTs</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta name="keywords" content="Capacitive, TFT, LCD, Liquid Crystal Display, diagonal, Color Display" />
    <meta name="description" content="Product listing for Newhaven Display's capacitive touch TFT displays." />
    <meta http-equiv="imagetoolbar" content="no" />
    <meta name="author" content="Curt Lagerstam" />
    <meta property="fb:page_id" content="218603224834427" />
    <meta property="fb:admins" content="user_id" />
    <meta property="fb:page_id" content="your_page_id" />
    <meta name="generator" content="" />
    
    <base href="http://localhost/" />
    
    <link rel="stylesheet" type="text/css" href="includes/templates/gloss_black/css/style_imagehover.css" />
    <link rel="stylesheet" type="text/css" href="includes/templates/gloss_black/css/stylesheet.css" />
    <link rel="stylesheet" type="text/css" href="includes/templates/gloss_black/css/stylesheet_compare.css" />
    <link rel="stylesheet" type="text/css" href="includes/templates/gloss_black/css/stylesheet_header_menu.css" />
    <link rel="stylesheet" type="text/css" href="includes/templates/gloss_black/css/stylesheet_smartbg.css" />
    <script type="text/javascript" src="includes/templates/gloss_black/jscript/jscript_jquery161.js"></script>
    <script type="text/javascript" src="includes/templates/gloss_black/jscript/jscript_rollovers.js"></script>
    <script type="text/javascript">
    <!--
      var GOOGLE_ANALYTICS_TRACKING_OUTBOUND_LINKS_PREFIX = "/outgoing/";
    //-->
    </script>
    <script type="text/javascript" src="includes/templates/gloss_black/jscript/googleanalytics_outgoing.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function(){ 
        $('#compareResult:not(:has(.compareAdded))').css("display", "none");
        for (index = 0; index < data.length; index++) {
            $("input[name='" + data[index] + "']").prop("checked",true);
        }
    });
    
    function compareNew(obj, action) {
        $('#compareResult').show();
        if ( $("input[name='" + obj + "']").is(":checked") && $("a[name='rmv" + obj + "']").length ) {
            if ( action == 'remove' ) {
            $("input[name='" + obj + "']").prop("checked",false);
            } else if ( action == 'add' ) { }
        }
        else if ( $("input[name='" + obj + "']").is(":checked") && $("a[name='rmv" + obj + "']").length === 0 ) { }
        else {
            action = 'remove';
        }
        $('#compareProducts').load('ajax_compare.php', {'compare_id': obj, 'action': action, 'securityToken': 32211a3feaf03d8d7608ccbb28f392c2});
        
    }
    
    
    
      function hideCompare() {
          $('#compareResult').hide();
      }
    </script>
    
    <link href="/includes/languages/english/html_includes/css/page_layout.css" rel="stylesheet" type="text/css" />
    <link href="/includes/templates/gloss_black/css/cloud-zoom.css" rel="stylesheet" type="text/css" />
    <link href="/includes/templates/gloss_black/css/lightbox.css" rel="stylesheet" type="text/css" />
    
    <script src="https://www.google.com/jsapi?key=ABQIAAAAdCtw6Xq1Q31YAr7VSQOSvxS5g7WKqCWUBuUdhz3-rUOumR2saRSPGvey2WjYALW7f5_JzakSL3lAEg" type="text/javascript"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    
    <script src="includes/templates/gloss_black/jscript/" type="text/javascript"></script>
    <script src="includes/templates/gloss_black/jscript/scriptaculous.js?load=effects" type="text/javascript"></script>
    <script src="includes/templates/gloss_black/jscript/lightbox.js" type="text/javascript"></script>
    
    
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/JavaScript" src="includes/templates/gloss_black/jscript/cloud-zoom.1.0.2.min.js"></script>
    
    
    	<script type="text/javascript">
    		$(function(){
    			$('.showmore').click(function(e){
    				var Wrapper = $(this).parents('.release');
    				Wrapper
    					.find('.hideThis')
    						.fadeOut(function(e){
    							Wrapper
    								.find('.hidden')
    									.fadeIn();
    						})
    				return false;
    			})
    		
    
    			$('.showless').click(function(e){
    				var Wrapper = $(this).parents('.release');
    				Wrapper
    					.find('.hidden')
    						.hide();
    				Wrapper
    					.find('.hideThis')
    						.fadeIn(function(e){
    							})
    				return false;
    			})	
    		})
    	</script>
    	<style>
    		.hidden{display:none}
    
    	</script>
    <style>
    		.hidden{display:none}
    	</style>
    
        
    <!--reCaptcha -->
        
    <!-- <script src='https://www.google.com/recaptcha/api.js'></script>-->   
        
        
        
        
    
    </head>
    Last edited by RobertH; 2 Feb 2016 at 08:24 PM. Reason: func not defined error

  9. #9
    Join Date
    Jan 2004
    Posts
    66,373
    Blog Entries
    7
    Plugin Contributions
    274

    Default Re: Using XHR Request for Ajax based on what product(s) are chosen

    I guess should have wrapped single-quotes around the <?php echo ...;?> part so that the token gets treated as a string.
    .

    Zen Cart - putting the dream of business ownership within reach of anyone!
    Donate to: DrByte directly or to the Zen Cart team as a whole

    Remember: Any code suggestions you see here are merely suggestions. You assume full responsibility for your use of any such suggestions, including any impact ANY alterations you make to your site may have on your PCI compliance.
    Furthermore, any advice you see here about PCI matters is merely an opinion, and should not be relied upon as "official". Official PCI information should be obtained from the PCI Security Council directly or from one of their authorized Assessors.

  10. #10

    Default Re: Using XHR Request for Ajax based on what product(s) are chosen

    Quote Originally Posted by DrByte View Post
    I guess should have wrapped single-quotes around the <?php echo ...;?> part so that the token gets treated as a string.
    Doesn't the whole $_SESSION [] variable need to be out of quotes to specifically *not* be treated as a string?

    I will try this tommorrow as I'm leaving work right now. Thank you for your responses today. I hope I've been providing more useful details - I don't mean to withhold I just try to only provide what's relevant so it's not a big long mess of stuff that mostly doesn't affect the problem.

    But I suppose the problem arises from me not knowing what is and is not relevant, huh.
    Last edited by RobertH; 2 Feb 2016 at 11:35 PM. Reason: quotes compromise variable?

 

 
Page 1 of 2 12 LastLast

Similar Threads

  1. v155 For what does ZC v155 make use of ajax?
    By carlwhat in forum General Questions
    Replies: 3
    Last Post: 21 Mar 2016, 11:40 PM
  2. Looking for a plugin that displays cart totals using AJAX
    By tcarden in forum General Questions
    Replies: 3
    Last Post: 12 Dec 2013, 07:33 PM
  3. v139h Anyone know of an Ajax based review/comment system in Product Detail page?
    By ivan999 in forum Templates, Stylesheets, Page Layout
    Replies: 0
    Last Post: 26 Jul 2012, 08:59 PM
  4. 2 AJAX based module for Zen-Cart, please review
    By jaycode in forum All Other Contributions/Addons
    Replies: 3
    Last Post: 13 Dec 2007, 05:01 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
disjunctive-egg
Zen-Cart, Internet Selling Services, Klamath Falls, OR