1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Trouble With Apostrophe

Discussion in 'PHP' started by Jeremy Benson, Oct 2, 2015.

  1. #1
    Hello,

    I have this script in PHP that gets available ad placements. The problem is some of them have apostrophes, which are causing problems in my JavaScript function. I'm not sure what I can do to fix the issue. I've tried Str replace in my UTF8_Make function, which I know is poor organization, but it didn't work anyway. For some reason when I json encode the entire array of placements it's not fixing the problem. Is there another solution?

    Thanks for any help,
    Jeremy.

    <?php
    
    session_start();
    
    if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['ID']))
    {
    
        require('../../data/sqldata.php');
       
        $takenPlacements = array();
        $availablePlacements = array();
       
        $db = new PDO($dsn, $dbUsername, $dbPassword, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
       
        // get all the taken placements
        $getTakenStm = $db->prepare('SELECT * FROM `ad_placements` WHERE `country` = ?');
    
        try{
           
            $getTakenStm->execute(array($_POST['country']));
            $takenPlacements = $getTakenStm->fetchAll();
           
        }catch(\PDOException $e){}
       
        // Get count of genres for available placements fetch.
       
        $genreCount = $db->query('SELECT count(*) FROM `genres`')->fetchColumn();
       
        // get all possible placements
       
        $getPlacementsStm = $db->prepare('SELECT `ID`, `mainGenre`, `genre`, `subGenre` FROM `genres` WHERE `ID` <= ?');
       
        try{
           
            $getPlacementsStm->execute(array($genreCount));
            $availablePlacements = $getPlacementsStm->fetchAll();
           
        }catch(\PDOException $e){ }
    
        if(!empty($takenPlacements))
        {
        // remove the taken placements from the possible placements   
            $count = count($availablePlacements);
            $removedBefore = array();
           
            for($i = 0; $i <= $count - 1; $i += 1)
            {  
                $availablePlacements = array_values($availablePlacements);
                $count = count($availablePlacements);
               
                if(isset($takenPlacements[$i]['ID']))
                {
                    // test normal placement space
                    $genres = explode('@', $takenPlacements[$i]['placement']);
                   
                    if($takenPlacements[$i]['placement'] != 'Special@Special@Index' && $takenPlacements[$i]['placement'] != 'Special@Special@Profile')
                    {
                        //get count from placements
                     $countStm = $db->prepare('SELECT * FROM `ad_placements` WHERE `placement` = ? AND `Country` = ?');
                   
                     try{
                   
                            $countStm->execute(array($takenPlacements[$i]['placement'],
                                                     $_POST['country']));
                            $normalPlacementCount = $countStm->rowCount();
                           
                     }catch(\PDOException $e){}
                   
                       
                        if($normalPlacementCount >= 2 && !in_array($takenPlacements[$i]['placement'], $removedBefore))
                        {
                            // There are too many of this placement, remove it from available placements
                            $removeIndex = 0;
                             // loop to capture index to remove.
                            for($j = 0; $j <= $count - 1; $j += 1)
                            {
                               
                                if($availablePlacements[$j]['mainGenre'] == $genres[0] &&
                                   $availablePlacements[$j]['genre'] == $genres[1] &&
                                   $availablePlacements[$j]['subGenre'] == $genres[2])
                                {
                                   
                                    $removeIndex = $j;
                                    unset($availablePlacements[$j]);
                                   
                                   
                                }
                               
                            }
                           
                           
                           
                            array_push($removedBefore, $takenPlacements[$i]['placement']);
                           
                        }
                   
                         // End test normal; start test index
                    }elseif($takenPlacements[$i]['placement'] == 'Special@Special@Index')
                    {
                       
                            $countStm = $db->prepare('SELECT * FROM `ad_placements` WHERE `placement` = ?');
                   
                    
                        try{
                   
                            $countStm->execute(array($takenPlacements[$i]['placement']));
                            $indexPlacementCount = $countStm->rowCount();
                           
                        }catch(\PDOException $e){}
                        
                            if($indexPlacementCount >= 1 && !in_array($takenPlacements[$i]['placement'], $removedBefore))
                            {   
    
                            // There are too many of this placement, remove it from available placements
                                $removeIndex = 0;
                             // loop to capture index to remove.
                            for($j = 0; $j <= $count - 1; $j += 1)
                            {
                               
                                if($availablePlacements[$j]['mainGenre'] == $genres[0] &&
                                   $availablePlacements[$j]['genre'] == $genres[1] &&
                                   $availablePlacements[$j]['subGenre'] == $genres[2])
                                {
                                   
                                    $removeIndex = $j;
                                    unset($availablePlacements[$j]);
                                   
                                   
                                   
                                }
                               
                            }
                           
                            array_push($removedBefore, $takenPlacements[$i]['placement']);
                           
                            }
                   
                        // end index test count, start profile
                    }elseif($takenPlacements[$i]['placement'] == 'Special@Special@Profile')
                    {
                       
                        $countStm = $db->prepare('SELECT * FROM `ad_placements` WHERE `placement` = ?');
                   
                    
                        try{
                   
                            $countStm->execute(array($takenPlacements[$i]['placement']));
                            $profilePlacementCount = $countStm->rowCount();
                           
                        }catch(\PDOException $e){}
                       
                        if($profilePlacementCount >= 2 && !in_array($takenPlacements[$i]['placement'], $removedBefore))
                            {   
                                // There are too many of this placement, remove it from available placements
               
                             // loop to capture index to remove.
                            for($j = 0; $j <= $count - 1; $j += 1)
                            {
                               
                                if($availablePlacements[$j]['mainGenre'] == $genres[0] &&
                                   $availablePlacements[$j]['genre'] == $genres[1] &&
                                   $availablePlacements[$j]['subGenre'] == $genres[2])
                                {
                               
                                    unset($availablePlacements[$j]);   
                               
                                }
                               
                            }
                               
                            array_push($removedBefore, $takenPlacements[$i]['placement']);
                           
                            }
                       
                        // end test count for profile placements
                    }
                   
                 // end of if takenPlacement['ID'] set, for testing placement count
                 }
             // end loop for looping through available placements               
            }
           
                // Re-index the array before sending it back           
                $availablePlacements = array_values($availablePlacements);
               
                // Send array back to JS
                echo json_encode(utf8make($availablePlacements));
                // end if $takenPlacements ! empty.
        }else{
                // send back full array, nothing to take away.
               
                echo json_encode(utf8make($availablePlacements));
        }
       
    }else{
       
        // go to index with error
       
    }
    
    function utf8make($arraySet)
    {
       
        for($i = 0; $i <= count($arraySet) - 1; $i += 1)
        {
           
            utf8_encode($arraySet[$i]['mainGenre']);
            utf8_encode($arraySet[$i]['genre']);
            utf8_encode($arraySet[$i]['subGenre']);
            str_replace("'", "\'", $arraySet[$i]['genre']);
            str_replace("'", "\'", $arraySet[$i]['mainGenre']);
            str_replace("'", "\'", $arraySet[$i]['subGenre']);
           
        }
       
        return $arraySet;
    }
    ?>
    PHP:
     
    Jeremy Benson, Oct 2, 2015 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    How does your dataset look when you receive it on the javascript end? Console log the return data, then paste it here (or just a line, if it's big)
     
    PoPSiCLe, Oct 2, 2015 IP
  3. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #3
    Thanks Popsicle. Here's a snippet of one with an apostrophe.
     
    Jeremy Benson, Oct 2, 2015 IP
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    You shouldn't need to escape either / nor '... That's after parseJSON I assume. On my phone now, so a bit hard to test, but I'm thinking there's something else messing with the result.
     
    PoPSiCLe, Oct 2, 2015 IP
  5. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #5
    That snippet is from the ajax response, so the only thing that has gone though is utf8_encode(), json_encode().

    The issue I'm having is with apostrophes though. I need all apostrophes escaped so they can be used as parameters in a JavaScript function.
     
    Jeremy Benson, Oct 2, 2015 IP
  6. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #6
    If they are being passed to a function they should already be in a variable after you decode it. Of course if you are using utf-8 your sql table should be set to that so you don't need to utf-8 encode the values either.

    You probably also shouldn't be needing to try/catch your prepare/exec unless you've done something REALLY wrong. You SHOULD be doing try/catch on creating the PDO object! Once you have a working object it's usually a waste to try and check that unless you're worried the tables might not exist or something totally jacked up like that.

    Though your having to uptree with ../../ also likely means your directory structure is banjaxed.

    Also if you're on a modern PHP and not some three year out of date nonsense, you can now just say [] instead of array()

    It's also usually in most cases a REALLY bad idea to use fetchAll.

    Also if your ID is an auto-increment if you delete a genre then add one, the count will NOT equal the last of the genre's. Not sure what you're even trying to accomplish with that. It's also a bad idea to use uppercase in your sql element names since some sql engines other than mysql could choke on that, and if you use something like phpmyadmin to make a backup it will mangle them when you try to restore the DB. (Admittedly I avoid that headache by creating SQL backups at the command line).

    I'm getting the feeling that all of that code should be just one query and a json_encode or array conversion and/or record creation with simplexml.

    I'm not quite certain what you're trying to accomplish for output from this, but it reeks of brute force coding (writing code to do something the language already has functions or methods to accomplish) and over-thinking the problem. That lack of being able to follow it may also come from sloppy code like multiple if/else on the same variable doing the job of switch/case with the order backwards (you check for != on both, but then == on each?!?)... though I REALLY have the feeling whatever it is you're trying to do, it needs far, FAR less queries and to NOT waste memory with the ::fetchAll method (that NEVER should have existed in the first place).

    I'm not even sure how you are expecting those two different queries to have the same array indexes since you seem to be using the same $i on both array results...
     
    deathshadow, Oct 2, 2015 IP
  7. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #7
    There's two different loops, and two different arrays. I'm getting taken placements from ad_placements, and getting available placements from genres. After that I remove anything that's taken from available. Then send the data to JavaScript.

    I now the code could be simplified, but not really sure how re-writing it will fair. I don't know why I had to us ut8, just know it didn't work in JavaScript until I did. Also don't know enough about databases to set them up professionally. I just need to know how to escape the apostrophe. It's the only thing breaking my code.
     
    Jeremy Benson, Oct 3, 2015 IP
  8. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #8
    Thats odd as the JSON_encode should be handling that for you. Could the problem be how you're decoding it client-side? What's the JS that's trying to parse this result?
     
    deathshadow, Oct 3, 2015 IP
  9. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #9
    I know what's in the code too. There is no processing what so ever that I did to the array values. All I did was remove matches from one array to another... the only thing that is processed in these.. is uf8, and json_encode... That's it, lol.
     
    Jeremy Benson, Oct 3, 2015 IP
  10. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #10
    This function recieves it
    this.get_placements  = function()
        {
           
            var placementData = {"country": this.country};
            // Send country to script get available spaces sent back as array or json.
           
            $.ajax({
                context:this,
                url: '../../php/scripts/get_ad_placements.php',
                type: 'POST',
                data: placementData
               
            }).done(function(results){
               
                this.availablePlacements = [];
                this.availablePlacements = JSON.parse(results);
                this.show_placements();
               
            });
           
        }
    Code (JavaScript):
    And this rather big function shows it..

    this.show_placements = function()
        {
           
            // add the placements to the cart, for user to browse.
                // must attach function for adding placement to cart.
           
             for(var i=0;i<this.availablePlacements.length;i++)
             {
           
                var obj = this.availablePlacements[i];
                for(var key in obj)
                {
                   
                    // echo out special placements
                    if(key == 'subGenre')
                    {
                       
                        if(obj[key] == 'Index' || obj[key] == 'Profile' || obj[key] == 'Search')
                        {
                           
                            $("#special").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj[key] + '</span></a></li>');
                       
                        }
                   
                       
                    }
                    
                     // output normal placements
                    if(key == 'mainGenre')
                    {
                       
                        if(obj[key] == 'Movies/Television')
                        {
                           
                            $("#movies-television").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj['subGenre'] + '</span></a></li>');
                           
                        }
                       
                        if(obj[key] == 'Music')
                        {
                           
                            $("#music").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj['genre'] + ' ' + obj['subGenre'] + '</span></a></li>');
                            //alert('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj[key] + '</span></a></li>');
    
                        }
                       
                        if(obj[key] == 'Games')
                        {
                           
                            $("#games").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj['subGenre'] + '</span></a></li>');
                           
                        }
                       
                        if(obj[key] == 'Magazines')
                        {
                           
                            $("#magazines").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj['subGenre'] + '</span></a></li>');
                           
                           
                        }
                       
                        if(obj[key] == 'Books')
                        {
                           
                            $("#books").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj['subGenre'] + '</span></a></li>');                       
                           
                        }
                       
                        // end of if key == mainGenre, output normal placements
                    }
                   
                    // end of for loop over availablePlacements
                }
               
                // End for loop over avaiablePlacements length
            }
       
         // end of show placements function
        }
    Code (JavaScript):
     
    Jeremy Benson, Oct 3, 2015 IP
  11. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #11
    One problem I had is with Kid's Movies... Here. The apostrophe is throwing out the function.
     
    Jeremy Benson, Oct 3, 2015 IP
  12. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #12
    Ah - I'm guessing it's the broken onclick-events that is causing the problems. If you remove those, and move the action to the javascript-file, I'm quite sure it will work just fine. (Don't use onclick-events, just catch whatever is being clicked and process it in the main js-file).
     
    PoPSiCLe, Oct 3, 2015 IP
  13. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #13
    Ah, see, it's that your using innerHTML that's causing the problem as JSON.parse unescapes them, and to innerHTML you'd have to re-escape them.

    Part of why I don't use jQuery, document.write or innerHTML. You also seem to be using an anchor

    This is the brute force scripted approach -- helper functions would make this simpler to deal with, but the overall idea is this:
    var
    	d = document,
    	li = d.createElement('li'),
    	a = li.appendChild(d.createElement('a')),
    	span = a.appendChild(d.createElement('span'));
    	
    li.id = obj['mainGenre'] + obj['genre'] + obj['subGenre'];
    span.appendChild(d.createTextNode(obj['subGenre']));
    
    a.data = obj;
    a.onclick = function(e) {
    	var t = (e = e || window.event).target || e.srcElement;
    	while (t && t.tagName && (t.tagName != 'A')) t = t.parentNode;
    	if (t) cart.cart_placement(
    		t.data['mainGenre'],
    		t.data['genre'],
    		t.data['subGenre']
    	);
    }
    
    d.getElementById('movies-television').appendChild(li);
    Code (markup):
    We create an LI as a independant DOM node (not part of the document), create the anchor and span inside said anchor (you really sure you need that span? Just asking...) then apply the properties we want to those objects. I pass your obj as a data property on the anchor so the onclick can handle it properly.

    NORMALLY to attach the onclick function you'd use addEventListener and it's cross-browser workaround, but since we JUST made the element we know it has no event properties so we can go ahead and attach to onclick directly.

    The function figures out which element sent the onclick (which should be the anchor) and extracts the data from it to pass to your global cart object's method. It's possible the span or textnode may incorrectly report as the source hence the "while" to up-tree check it. I check if (t) since it's possible to have a mis-report on that. Error handling is your friend.

    We then attach the LI to the end of that parent element putting it into the document.

    Which as complex as that might seems, is faster, cleaner and more reliable than trying to blindly paste together markup and hope that it works. It's why we've been told for over a decade by the ECMA standards folks to STOP using innerHTML, STOP using document.write, and it's one of the reasons that jQuery is a steaming pile of halfwit nonsense since much of its functionality is BASED on that broken outdated methodology.
     
    deathshadow, Oct 3, 2015 IP
  14. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #14
    I have no idea where to put that.. also there's more areas than just Movies/Television. If I knew where that code was supposed to go I might have a better idea of how to tailor it to everything else...
     
    Jeremy Benson, Oct 3, 2015 IP
  15. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #15
    I'm horrible at code I haven't written. Other people's code is like Chinese to me..
     
    Jeremy Benson, Oct 3, 2015 IP
  16. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #16
    Okay, I got this figured out, but I'm getting the same error:
    'SyntaxError: missing ) after argument list'

    This happens when clicking Kid's Movies.
     
    Jeremy Benson, Oct 3, 2015 IP
  17. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #17
    Okay,

    I've updated the code, but I think WAMP is being stupid. One time before I was working on scripts, and I updated code, put the files in my www folder, and the site still ran like the old code was in there. I had to backup my db, uninstall wamp, and re-install it for the changed code to run like it was written. I don't know what caused that to happen... and I'm starting to suspect it here... so I may need to uninstall and reinstall to see if your code is right. Do you have any idea of what would cause that?

    Edit: I've uninstalled WAMP and reinstalled, but there's still issues. For some reason the alerts aren't alerting when the functions are called. The placements are being shown though. I have no idea if WAMP is running the old code, or new code, I don't have a clue what's up. All I know is I wiped out WAMP, deleted WWW folder, and started fresh.

    Here's the code too:

    this.show_placements = function()
        {
          
            // add the placements to the cart, for user to browse.
                // must attach function for adding placement to cart.
            alert('Obviously An Issue in show placements.');
             for(var i=0;i<this.availablePlacements.length;i++)
             {
          
                var obj = this.availablePlacements[i];
                for(var key in obj)
                {
                  
                    // echo out special placements
                    if(key == 'subGenre')
                    {
                      
                        if(obj[key] == 'Index' || obj[key] == 'Profile' || obj[key] == 'Search')
                        {
                          
                            $("#special").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj[key] + '</span></a></li>');
                      
                        }
                  
                      
                    }
                   
                     // output normal placements
                    if(key == 'mainGenre')
                    {
                      
                        if(obj[key] == 'Movies/Television')
                        {
                            alert("HERE WE ARE!!!!");
                            var
                                d = document,
                                li = d.createElement('li'),
                                a = li.appendChild(d.createElement('a')),
                                span = a.appendChild(d.createElement('span'));
                              
                            li.id = obj['mainGenre'] + obj['genre'] + obj['subGenre'];
                            span.appendChild(d.createTextNode(obj['subGenre']));
    
                            a.data = obj;
                            a.onclick = function(e) {
                                var t = (e = e || window.event).target || e.srcElement;
                                while (t && t.tagName && (t.tagName != 'A')) t = t.parentNode;
                                if (t) cart.cart_placement(
                                    t.data['mainGenre'],
                                    t.data['genre'],
                                    t.data['subGenre']
                                );
                                alert('THIS WORKS!!');
                            }
                            alert('THIS WORKS!!');
                            d.getElementById('movies-television').appendChild(li);                      
                        }
                      
                        if(obj[key] == 'Music')
                        {
                          
                            $("#music").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj['genre'] + ' ' + obj['subGenre'] + '</span></a></li>');
                            //alert('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj[key] + '</span></a></li>');
    
                        }
                      
                        if(obj[key] == 'Games')
                        {
                          
                            $("#games").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj['subGenre'] + '</span></a></li>');
                          
                        }
                      
                        if(obj[key] == 'Magazines')
                        {
                          
                            $("#magazines").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj['subGenre'] + '</span></a></li>');
                          
                          
                        }
                      
                        if(obj[key] == 'Books')
                        {
                          
                            $("#books").append('<li id="'+ obj['mainGenre'] + obj['genre'] + obj['subGenre'] +'"><a onclick="cart.cart_placement(' + '\'' + obj['mainGenre'] + '\'' + ',' + '\'' + obj['genre'] + '\'' + ',' + '\'' + obj['subGenre'] +  '\'' + ')"><span>' + obj['subGenre'] + '</span></a></li>');                      
                          
                        }
                      
                        // end of if key == mainGenre, output normal placements
                    }
                  
                    // end of for loop over availablePlacements
                }
              
                // End for loop over avaiablePlacements length
            }
      
         // end of show placements function
        }
    Code (JavaScript):
     
    Last edited: Oct 3, 2015
    Jeremy Benson, Oct 3, 2015 IP
  18. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #18
    Alright, this is solved :) You're code works fine. There was some issues with browser cache, and likely transfering files. I just closed every browser window, and file in notepad++. Then I made sure I was working from the right folders and files, refreshed the browsers, and everything works fine. Thanks for helping me with this issue. Frig'n means a lot. Got another chunk of my site working, and can now focus on other bits of code... After that I'm gonna do everything in the security sector. Already took all my DB variables out of the classes as globals, and fed them to private data, using functions... Things will shape up once the site is done... I'll be asking more security related questions by then.. Thanks again .
     
    Jeremy Benson, Oct 3, 2015 IP
  19. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #19
    Some advice, if you're doing the same thing over and over again, don't do the same thing over and over again. You should also REALLY look into the case/switch mechanism instead of redundant IF statements... and if you WERE to be checking the same value, that's what ELSE is for, otherwise both conditions get run regardless of which is true.

    this.show_placements = function() {
    	
    	var
    		d = document,
    		obj, li, a, span; // predeclare to reduce memory thrashing
    	
    	function placementClick(e) { // declare procedure ahead of time so as to avoid redundant parsing
    	
    		var t = (e = e || window.event).target || e.srcElement;
    		while (t && t.tagName && (t.tagName != 'A')) t = t.parentNode;
    		if (t) cart.cart_placement(
    				t.data['mainGenre'],
    				t.data['genre'],
    				t.data['subGenre']
    		);
    		
    	} // placementClick
    	
    	for (var i = 0; i < this.availablePlacements.length; i++) {
    	
    		obj = this.availablePlacements[i];
    		
    		for (var key in obj) {
    		
    			li = d.createElement('li');
    			li.id = obj['mainGenre'] + obj['genre'] + obj['subGenre'];
    			
    			a = li.appendChild(d.createElement('a')),
    			a.data = obj;
    			a.onclick = placementClick;
    			span = a.appendChild(d.createElement('span'));
    
    				
    			switch (key) {
    			
    				case 'subGenre':
    				
    					if (
    						obj[key] == 'Index' ||
    						obj[key] == 'Profile' ||
    						obj[key] == 'Search'
    					) {
    						span.appendChild(d.createTextNode(obj[key]));
    						d.getElementById('special').appendChild(li);
    					}
    					
    				break; // 'subGenre'
    				
    				case 'mainGenre':
    				
    					/*
    						I probably would NOT have these hardcoded and instead
    						have the ID be the same as the key... Just saying. Then
    						you could axe all the conditional checks entirely and you
    						wouldn't have to edit this every blasted time you want a new
    						genre/subgenre
    					*/
    				
    					switch (obj[key]) {
    					
    						case 'Movies/Television':
    							span.appendChild(d.createTextNode(
    								obj['subGenre']
    							));
    							d.getElementById('movies-television').appendChild(li);
    						break;
    						
    						case 'Music'':
    							// Why is this different? Just curious...
    							span.appendChild(d.createTextNode(
    								obj['genre'] + ' ' + obj['subGenre']
    							));
    							d.getElementById('music').appendChild(li);
    						break;
    						
    						case 'Games':
    							span.appendChild(d.createTextNode(
    								obj['subGenre']
    							));
    							d.getElementById('games').appendChild(li);
    						break;
    						
    						case 'Magazines':
    							span.appendChild(d.createTextNode(
    								obj['subGenre']
    							));
    							d.getElementById('magazines').appendChild(li);
    						break;
    						
    						case 'Books':
    							span.appendChild(d.createTextNode(
    								obj['subGenre']
    							));
    							d.getElementById('books').appendChild(li);
    						break;
    						
    					} // switch obj[key]
    					
    				break; // 'mainGenre'
    				
    			} // switch (key)
    									
    		} // for key in obj
    		
    	} for availableReplacements
    	
    } // this.showPlacements
    Code (markup):
    I'd probably have the keys be a valid HTML ID and store the text you want to show as a separate value -- that way you could get rid of the inner case entirely.

    Also, why is 'music' different from the others? If it's not supposed to be you could move all those appendChild to before that specific case/switch instance.
     
    deathshadow, Oct 4, 2015 IP