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.

Problem with Classes and Ajax

Discussion in 'JavaScript' started by Jeremy Benson, Apr 21, 2017.

  1. #1
    I've got trouble with a JS class, and ajax call. Never had this many problems with something so easy in a while, lol. The axaj won't work, but even simpler lastID is always undefined. Not sure what's up.

    var communityObj = new Community('none');
    
    function Community(IDSET){
    
       var lastID = IDSET;
        
      this.fetch = function()
       {
        
          var ID = this.return_id();
        
          alert(ID);
          
           // ajax call to select x number of
    
           $.ajax({
            url: "php/handle_community_scroll_sleuths.php",
            method:"POST"
            data:{idObj:ID}
           }).done(function( data ) {
              alert(data);
            });
         
        
       };
      
       this.return_id = function()
       {
        
         return this.lastID;
        
       }
      
    }
    Code (markup):

     
    Jeremy Benson, Apr 21, 2017 IP
  2. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #2
    I solved this issue, but found a new bug. I instantiate html to an empty string, and append to it in a couple of ajax calls, but when I get to the end of the function the sting is empty. Not sure why.

    function Community(IDSET){
    
        this.lastID = IDSET;
          
        this.fetch = function()
        {
           
            var ID = this.return_id();
            var html = '';
            
                // ajax call to select x number of
               
                $.ajax({
                  url: "php/handle_community_scroll_sleuths.php",
                  method:"POST",
                 dataType: "json",
                  data:{idObj:ID}
                }).done(function( data ) {
                    
                     for(i = 0; i <= data.length; i++)
                     {
                        
                         html += "<div class=\"panel\"> \
                                        <div class=\"sleuth\"> \
                                                    <img class=\"img-circle\" src=\"images/profile.jpg\" height=\"34\" width=\"34\" /> \
                                                    <span><b>JeremyBenson11</b> > TYPE</span><br><br> \
                                                    <p class=\"sleuth-text\">DESC</p> \
                                                    <p style=\"margin-top:12px;\"> \
                                                        <a href=\"php/handle_like_sleuth.php?token=&username=\"><i style=\"margin-right:6px;\" class=\"fa fa-thumbs-o-up\"></i></a><b style=\"margin-left:8px;\"></b> \
                                                        <i style=\"margin-left:12px;\" class=\"fa fa-comment-o\"></i> COUNT \
                                                        <i style=\"margin-left:12px; margin-right:4px;\" class=\"fa fa-retweet\"></i> repost \
                                                        <i style=\"margin-left:12px; margin-right:4px;\" class=\"fa fa-retweet\"></i> page</p> \
                                                    <hr> \
                                                    <a href=\"\" target=\"_BLANK\" >Title</a> \
                                                    <hr>";
                                                   
                                        // Fetch comments for the sleuth
                       
                                    var sleuthToken = data[i].token;
                                                               
                                                               
                                    $.ajax({
                                      url: "php/handle_community_fetch_sleuth_comments.php",
                                      method:"POST",
                                     dataType: "json",
                                     data:{token:sleuthToken}
                                    }).done(function( commentData ) {
                               
                                   
                                            if(data.length >= 1)
                                            {
                                                html += "<div class=\"comments\" style=\"overflow-y:scroll;max-height:24em;\">";
                                                   
                                                for(i = 0; i<data.lenght; i++)
                                                {
                                                       
                                                    html += "<div class=\"comment\">" +
                                                                "<h5><b>USERNAME</b></h5>" +
                                                                    "<p>COMMENT</p>" +
                                                                "<a href=\"php/handle_like_sleuth_comment.php?token=&username=&page=community\"><i style=\"margin-right:6px;\" class=\"fa fa-thumbs-o-up\"></i></a><b style=\"margin-left:8px;\">LIKES</b>" +
                                                            "</div>";
                                                       
                                                }
                                               
                                                    html += "</div>";
                                                   
                                            }       
                                                           
                                        // End fetch comments ajax
                                    });
                                                                   
                                            html += "<hr> \
                                                <form method=\"POST\" action=\"php/handle_comment_sleuth.php\"> \
                                                    <textarea rows=\"4\" style=\"width:100%;\" name=\"comment\"></textarea> \
                                                    <input type=\"hidden\" name=\"token\" value=\"TOKEN\" /> \
                                                    <input type=\"hidden\" name=\"username\" value=\"USERNAME\" /> \
                                                    <input style=\"float:right;margin-top:8px;\" class=\"post-button btn btn-primary\" type=\"submit\" value=\"POST\" /> \
                                                </form> \
                                            <div style=\"clear:both;\"></div> \
                                        </div></div>";
                                        
    
                    }
                    
                        // End fetch sleuths ajax
                  });
           
            alert(html);
            // END Fetch Function
        };
       
        this.return_id = function()
        {
            return this.lastID;
           
        };
      
    }
    
    
                                           
                                           
                                               
                                        
    Code (markup):
     
    Jeremy Benson, Apr 21, 2017 IP
  3. sarahk

    sarahk iTamer Staff

    Messages:
    28,500
    Likes Received:
    4,460
    Best Answers:
    123
    Trophy Points:
    665
    #3
    so if you use console.log(html) through the function you can see html getting created and suddenly wiped?
     
    sarahk, Apr 22, 2017 IP
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    There are a few issues - among them, some superfluous backslashes in the last html-block. BTW, wrap the HTML in single quotes, instead of double quotes, and you won't need to escape every double quote inside the HTML (you will need to escape single quotes instead, but that is a lot less invasive). Also, better than using + or any other concatination, just write the HTML and then remove extra linebreaks/spaces - ie, make a whole HTML-block without line breaks and such, which will save you a bit of code and make it a bit easier to make sure your variable actually contains what you want it to contain.
     
    PoPSiCLe, Apr 22, 2017 IP
    sarahk likes this.
  5. mmerlinn

    mmerlinn Prominent Member

    Messages:
    3,197
    Likes Received:
    818
    Best Answers:
    7
    Trophy Points:
    320
    #5
    I see two potential problems.

    First, it appears that there is at least one mispelt word which needs to be fixed.

    Second, it appears that you are running two loops, one inside the other, both with the same variable name. Generally, loops like that will not work properly. Use different variable names for nested loops.
     
    mmerlinn, Apr 22, 2017 IP
  6. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #6
    Thanks guys. Appreciate the comments. I was able to get this to partway work. I'm trying to fix it by chaining the ajax through promises. I need four ajax calls to run, one after another. In that order, with them starting when the one before finishes. My posts are coming out, but despite getting three returned from php, it's looping out six.

    Here's the new code, trying to utilize $.when. As far as I know it's never being called. There's no alert. Also the html loops should be placed in the when, looping over index 0 of the .done, right?

    Also used Popsicle's advice, mostly. Just not the long string of html :p

    
    var fetchSleuth = $.ajax({
            method:"POST",
            url: "php/handle_community_scroll_sleuths.php",
            dataType: "json"
           }).done(function( data ) {
           
              for(i = 0; i <= data.length; i++)
              {
                       
                html += '<div class="sleuth"> \
                 <img class="img-circle" src="imagesprofile.jpg" height="34" width="34" /> \
                             <span><b>'+data[i].username+'</b> > '+data[i].type+'</span><br><br> \
                             <p class="sleuth-text">'+data[i].description+'</p> \
                             <p style="margin-top:12px;"> \
                               <a href="php/handle_like_sleuth.php?token="+data[i].token+"&username="+data[i].username+"&page=community"><i style="margin-right:6px;" class="fa fa-thumbs-o-up"></i></a> '+data[i].likes+'<b style="margin-left:8px;"></b> \
                               <i style="margin-left:12px;" class="fa fa-comment-o"></i> <span id="commentscount'+data[i].token+'"></span> \
                               <i style="margin-left:12px; margin-right:4px;" class="fa fa-retweet"></i> repost \
                               <i style="margin-left:12px; margin-right:4px;" class="fa fa-retweet"></i> page</p> \
                             <hr> \
                             <a href="'+data[i].link+'" target="_BLANK" >'+data[i].title+'</a> \
                             <hr> \
                             <div id="'+data[i].token+'" class="comments" style="overflow-y:scroll;max-height:24em;"></div>';
                           
                       // Fetch comments for the sleuth
                           
                         html += '<hr> <form method="POST" action="php/handle_comment_sleuth.php"> \
                             <textarea rows="4" style="width:100%;" name="comment"></textarea> \
                             <input type="hidden" name="token" value="TOKEN" /> \
                             <input type="hidden" name="username" value="USERNAME" /> \
                             <input style="float:right;margin-top:8px;" class="btn btn-primary" type="submit" value="POST" /> \
                           </form> \
                         <div style=\"clear:both;\"></div> \
                       </div>';
                       
                       $('#sleuthswrapper').append(html);
    
             }   
       
               // End fetch sleuths ajax
            }),
           
            fetchSleuthCommentCount = $.ajax({
            url: "php/handle_fetch_sleuth_comment_count.php",
            method:"POST",
           // dataType: "html",
            data:{token:sleuthToken}
           }).done(function( commentsCountData ) {
                       
             $('#commentscount' + sleuthToken).append(commentsCountData);
                   
           }),
         
         
           fetchSleuthComments = $.ajax({
             url: "php/handle_community_fetch_sleuth_comments.php",
              method:"POST",
              dataType: "json",
              data:{token:sleuthToken}
           }).done(function( commentData ) {
                   
             if(data.length >= 1)
             {
                         
                           
               for(i = 0; i<commentData.length; i++)
               {
                             
                 var commentHtml = '<div class="comment"> \
                           <h5><b>'+commentData[i].username+'</b></h5> \
                             <p>'+commentData[i].comment+'</p> \
                           <a href="php/handle_like_sleuth_comment.php?token='+commentData[i].token+'&page=community"><i style="margin-right:4px;" class="fa fa-thumbs-o-up"></i></a><span>'+commentData[i].likes+' likes</span> \
                             </div>';
                       
                 $('#'+sleuthToken).append(commentHtml); 
             
               }
           
               selfObj.fetch_comment_comments_count(sleuthToken);
                           
             }   
                       // End fetch comments ajax
           }),
         
         
           fetchSleuthCommentCommentsCount =    $.ajax({
                                url: "php/handle_fetch_sleuth_comment_count.php",
                                method:"POST",
                               // dataType: "html",
                               data:{token:sleuthToken}
                               }).done(function( commentsCountData ) {
                                         
                                 $('#commentscount' + sleuthToken).append(commentsCountData);
                                       
                               });
       
         
           $.when(fetchSleuth, fetchSleuthCommentCount, fetchSleuthComments, fetchSleuthCommentCommentsCount).done(function(sleuthData, sleuthCommetnsCountData, sleuthCommentsData, sleuthCommentCommentsCountData){
           
             alert('done');
           
           
           });
                 
    Code (markup):
     
    Last edited: Apr 23, 2017
    Jeremy Benson, Apr 22, 2017 IP
  7. mmerlinn

    mmerlinn Prominent Member

    Messages:
    3,197
    Likes Received:
    818
    Best Answers:
    7
    Trophy Points:
    320
    #7
    One of the first things I would do is to simplify your naming conventions. You have too many function & variable names very similar to each other making it very hard to follow the code and very easy to misplace/misspell them. You corrected the previous misspelt word(s), but have one or more new ones that need to be corrected.
     
    mmerlinn, Apr 23, 2017 IP
  8. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #8
    Could you point out the spelling error? I'm not seeing it. I did knock an ajax call of the end. I'm a bit confused.

    I've added an image so you can see the page.

    https://ibb.co/dt1yY5

    A sleuth is an investigator, like a PI.

    fetchSleuth = fetch them from the db, all the data for putting in a sleuth wrapper.
    fetchSleuthCommentCount = Fetch count of comments attached to the sleuth or post.
    fetchSleuthComments = Fetch comments attached to the post

    Here is updated code in function. I'm still getting too many out, with no comments attached. Comment count isn't attaching either. The code is different, not sure if it's in the right direction.

    
    this.fetch_first = function()
       {
         // fetch first six objects and store last ID in class lastID   
             
           var html = '';
           // ajax call to select x number of records
           
           var fetchSleuth = $.ajax({
            method:"POST",
            url: "php/handle_community_scroll_sleuths.php",
            dataType: "json"
           }).done(function( data ) {
             
              for(i = 0; i <= data.length; i++)
              {
                         
                html += '<div class="sleuth"> \
                 <img class="img-circle" src="images/profile.jpg" height="34" width="34" /> \
                             <span><b>'+data[i].username+'</b> > '+data[i].type+'</span><br><br> \
                             <p class="sleuth-text">'+data[i].description+'</p> \
                             <p style="margin-top:12px;"> \
                               <a href="php/handle_like_sleuth.php?token="+data[i].token+"&username="+data[i].username+"&page=community"><i style="margin-right:6px;" class="fa fa-thumbs-o-up"></i></a> '+data[i].likes+'<b style="margin-left:8px;"></b> \
                               <i style="margin-left:12px;" class="fa fa-comment-o"></i> <span id="commentscount'+data[i].token+'"></span> \
                               <i style="margin-left:12px; margin-right:4px;" class="fa fa-retweet"></i> repost \
                               <i style="margin-left:12px; margin-right:4px;" class="fa fa-retweet"></i> page</p> \
                             <hr> \
                             <a href="'+data[i].link+'" target=\"_BLANK\" >'+data[i].title+'</a> \
                             <hr> \
                             <div id="'+data[i].token+'" class="comments" style="overflow-y:scroll;max-height:24em;"></div>';
                             
                       // Fetch comments for the sleuth
                             
                         html += '<hr> <form method="POST" action="php/handle_comment_sleuth.php"> \
                             <textarea rows="4" style="width:100%;" name="comment"></textarea> \
                             <input type="hidden" name="token" value="TOKEN" /> \
                             <input type="hidden" name="username" value="USERNAME" /> \
                             <input style="float:right;margin-top:8px;" class="btn btn-primary" type="submit" value="POST" /> \
                           </form> \
                         <div style=\"clear:both;\"></div> \
                       </div>';
                         
                       $('#sleuthswrapper').append(html);
                         
                       
                       
    
                       
             }     
         
               // End fetch sleuths ajax
            }),
             
            fetchSleuthCommentCount = $.ajax({
            url: "php/handle_fetch_sleuth_comment_count.php",
            method:"POST",
           // dataType: "html",
            data:{token:sleuthToken}
           }).done(function( commentsCountData ) {
                         
             $('#commentscount' + sleuthToken).append(commentsCountData);
                     
           }),
           
           
           fetchSleuthComments = $.ajax({
             url: "php/handle_community_fetch_sleuth_comments.php",
              method:"POST",
              dataType: "json",
              data:{token:sleuthToken}
           }).done(function( commentData ) {
                     
             if(data.length >= 1)
             {
                           
                             
               for(i = 0; i<commentData.length; i++)
               {
                               
                 var commentHtml = '<div class="comment"> \
                           <h5><b>'+commentData[i].username+'</b></h5> \
                             <p>'+commentData[i].comment+'</p> \
                           <a href="php/handle_like_sleuth_comment.php?token='+commentData[i].token+'&page=community"><i style="margin-right:4px;" class="fa fa-thumbs-o-up"></i></a><span>'+commentData[i].likes+' likes</span> \
                             </div>';
                         
                 $('#'+sleuthToken).append(commentHtml);   
               
               }
             
                             
             }     
                       // End fetch comments ajax
           });
           
         
           
           $.when(fetchSleuth, fetchSleuthCommentCount, fetchSleuthComments).done(function(data, commentsCountData, commentData){
             
             alert('done');
             
             
           });
           
       
         // end fetch first
       };
    
    Code (markup):
     
    Last edited: Apr 23, 2017
    Jeremy Benson, Apr 23, 2017 IP
  9. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #9
    I have a question. Would it be easier to build the html on the server side, and fetch them with on ajax calls?

    Axaj call -> fetch first three sleuth posts

    server side construct html.

    returned html gets displayed from JS

    Same with scroll to bottom.
     
    Jeremy Benson, Apr 23, 2017 IP
  10. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #10
    Okay, I did that. I learned a valuable lesson for myself. When I can be on the server, be on the server, lol.

    So I got the first bit down to a single ajax call. This pops out the first three sleuth posts. I'd like to fetch the comments in a second ajax call, but that brings me back to the same issue. How do I chain them? At least this is easier on the eyes now.

    this.fetch_first = function()
        {
            // fetch first six objects and store last ID in class lastID   
    
                // ajax call to select x number of records
               
                var fetchSleuth = $.ajax({
                  method:"POST",
                  url: "php/handle_community_scroll_sleuths.php"
                }).done(function( data ) {
                               
                    $('#sleuthswrapper').append(data);
                                                   
                        // End fetch sleuths ajax
                  })   
            // end fetch first
        };
    Code (markup):
     
    Jeremy Benson, Apr 23, 2017 IP
  11. mmerlinn

    mmerlinn Prominent Member

    Messages:
    3,197
    Likes Received:
    818
    Best Answers:
    7
    Trophy Points:
    320
    #11
    Hell of a lot easier on the eyes.

    Misspellings I saw (may have been others):

    1) lenght instead of length
    2) commetns instead of comments

    Now you have a problem with your syntax using {, {, ), and ). Fix that and see if that helps.

    P.S. I have never used ajax, never done server side, and almost never use javascript, so I am too much of an ignoramus to answer most of your questions.
     
    mmerlinn, Apr 23, 2017 IP
  12. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #12
    Hey, thanks :) I got the comments in. I'm facing a new problem. I'd like to add a click event to a dynamic button. I've tried everything.

    Here is my JS.

    $(function(){
    
      communityObj = new Community();
    
      communityObj.resetID();
      communityObj.fetch_first();
    
           $('.sleuth').on("click", "button.commentsubmit" , function() {
    
                alert('clicked');
    
            });
    });
        
    Code (markup):
    The html copied from php.

    <div title="'.$final[$key]['ID'].'" class="sleuth" token="'.$final[$key]['token'].'">
                            <img class="img-circle" src="images/profile.jpg" height="34" width="34" />
                                                    <span><b>'.$final[$key]['username'].'</b> > '.$final[$key]['type'].'</span><br><br>
                                                    <p class="sleuth-text">'.$final[$key]['description'].'</p>
                                                    <p style="margin-top:12px;">
                                                        <a href="php/handle_like_sleuth.php?token='.$final[$key]['token'].'&username='.$final[$key]['username'].'&page=community"><i style="margin-right:6px;" class="fa fa-thumbs-o-up"></i></a> '.$final[$key]['likes'].'<b style="margin-left:8px;"></b>
                                                        <i style="margin-left:12px;" class="fa fa-comment-o"></i> <span id="commentscount'.$final[$key]['token'].'">'.$count.'</span>
                                                        <i style="margin-left:12px; margin-right:4px;" class="fa fa-retweet"></i> repost
                                                        <i style="margin-left:12px; margin-right:4px;" class="fa fa-retweet"></i> page</p>
                                                    <hr>
                                                    <a href="'.$final[$key]['link'].'" target=\"_BLANK\" >'.$final[$key]['title'].'</a>
                                                    <hr>
                                                    <div id="'.$final[$key]['token'].'" token="'.$final[$key]['token'].'" last="0" class="comments" style="overflow-y:scroll;max-height:24em;"></div>
                                                    <hr>
                                                    <textarea rows="4" style="width:100%;" name="comment"></textarea>
                                                    <input type="hidden" name="token" value="'.$final[$key]['token'].'" />
                                                    <input type="hidden" name="username" value="'.$final[$key]['username'].'" />
                                                    <input type="hidden" name="page" value="community" />
                                                    <button token="'.$final[$key]['token'].'" style="float:right;margin-top:8px;" class="btn btn-primary commentsubmit">POST</button>
                                            <div style="clear:both;"></div>
                                        </div>
    Code (markup):
     
    Jeremy Benson, Apr 24, 2017 IP