Jump to content

TechnoDiver

Members
  • Posts

    203
  • Joined

  • Last visited

Recent Profile Visitors

2,198 profile views

TechnoDiver's Achievements

Advanced Member

Advanced Member (4/5)

2

Reputation

2

Community Answers

  1. Hi Freaks, I've been working on an issue trying to get an infinite scrolling system to work. I originally posted about it here -> I've been trying to debug and figure out the issue as I was pretty sure it was in the jquery/ajax script and not my PHP. The original script I'm using is in the original post linked above bur for reader convenience I'll post it again here -> <script> var userLoggedIn = '<?php echo $user->data()->username; ?>'; $(document).ready(function() { $('#loading').show(); //ajax for loading first posts $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=1&userLoggedIn=" + userLoggedIn, cache: false, success: function(data) { $('#loading').hide(); $('.posts_area').html(data); } }); $(window).scroll(function() { var height = $('.posts_area').height(); //div containing posts var scroll_top = $(this).scrollTop(); var page = $('.posts_area').find('.nextPage').val(); var noMorePosts = $('.posts_area').find('.noMorePosts').val(); if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { $('#loading').show(); var ajaxReq = $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=" + page + "&userLoggedIn=" + userLoggedIn, cache: false, success: function(response) { $('.posts_area').find('.nextPage').remove(); //removes current next page $('.posts_area').find('.noMorePosts').remove(); //removes current next page $('#loading').hide(); $('.posts_area').append(response); } }); } // end if return false; }); }); </script> the issue that I found is in the if statement condition-> if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { I added some console logs-> .... console.log("This is the scrollHeight: " + document.body.scrollHeight); console.log("This is the scrollTop: " + document.body.scrollTop); console.log(""); console.log("This is scrollTop + innerHeight: " + (document.body.scrollTop + window.innerHeight)); console.log(""); if((document.body.scrollTop + window.innerHeight >= 2500) && noMorePosts == 'false') { $('#loading').show(); console.log('This is fucked up'); // noMorePosts = true; ....... And it turns out that the overflow comments were being displayed but I had to scroll alll the way to the bottom of the page for it to happen. In the above code you can see where I altered the if condition to get the overflow comments to display sooner. This seems like a really bad fix to me as it's such an absolute value (2500) and doesn't take into account so many different variables in user system, setup etc etc. Also, at times it will load the overflow comments more than once. I've seen them repeated up to 3-4 times, which is certainly not acceptable. So I have 2 questions about this issue that I'm really hoping someone can help me resolve: 1) What is a more appropriate fix for the if condition rather than having that hardcoded 2500 in there? 2) What are some ways I can fix the sometimes repetitive overflow comments displaying? As I said in my original post, this jquery/ajax isn't my code and I'm trying to work through it when I get the time, but there is no mechanism in it to make noMorePosts = true and my commented out attempt at it didn't work. To say that I'm really uncomfortable with jquery and ajax would be an understatement. I look forward to reading your responses and hope a great weekend to you all. TIA
  2. Ok, I understand exactly what you're saying and I thought I addressed this with starting $count = 1. That way after the loop runs 10 times ($limit) than $count = 11 and is therefore > $limit. This is why I'm really lost on it. Even after displaying the first 10 posts it's actually not adding the else string to the end -> $str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align: centre;'> No more posts to show!</p>"; because I'm not seeing 'No more posts to show!' as I do if I change the '>' operator to '<' or '=' or '<=' in the same if statement, for example. So I don't really know where to go from here. I feel my PHP is, at least logically sound, though I know I'm no great coder, and I keep getting my head stuck on the Ajax. Which isn't my code, as I stated before, but I've been studying it and outside the 2 seemingly useless variables height and scroll_top it seems to my very untrained eye it should do something lol. Have I missed something in my PHP logic? I've looked at it 100,000 times
  3. Thanks for taking the time on that response, kicken, it gave me a lot to think about and I managed to get the posts displayed, so at least part of the ajax script is working, but it only displays the top 10 ($limit) and the infinite scroll part of it still isn't working. I've been reading articles, watching videos and staring at it on and off for hours trying to familiarize myself with what the jquery/ajax is actually doing, still have figured it out. Everything in the dev tools seems as it should be. I get the 200 response for the ajax_load file and it helped me fix my mistake that stopped any posts from loading to where I am now - first ten posts load, none of the others do when scrolling. The URL doesn't even change, which I assume it would after hit the scroll point that loads the posts, from the looks of the code. If you have any other suggestions I'm open to hearing anything on the matter. I feel like a baby in the woods trying to get this jquery working Yea, you've given me a whole new dimension to consider. Total noob mistake not seeing that that would be a problem. I'm going to keep it like is for now, only because the project isn't live and I'm also feeling completely overwhelmed by this particular task in the project and I feel that when I get the infinite scroll working properly I can use it as an anchor point while I mess with all the things wrong that I'll need to correct
  4. No, that's not alright with me actually, I'm just experienced enough to have foreseen it, I'm still trying to get my head around this AJAX. Was doing that as the notification for this comment popped-up actually. I'm certainly glad you pointed it out though. What would you suggest??
  5. So this is kind of a carry on from my last post about while looping, but I felt it was better to start it in a new thread because the framing of the question has changed. For those of you who responded to my last post I thank you and here is the issue and backstory on that post: I'm trying to integrate an AJAX infinite scrolling system into a project. I'm really uncomfortable with AJAX and have watched a few tutorials on it and have tried to integrate what I've learned into my PHP. The one tutorial that made the most sense to me also, obviously uses some PHP but it's kept at a basic level and the PHP of my own that I'm integrating it with is quite a bit more in depth. Before I start with the breakdown, I'd like to make clear that I'm not ignoring anyone's advice on using a foreach over the while loop. The ajax guy is using a while loop in his more simple examples and since I'm so uncomfortable with AJAX I wanted to stay as true to his examples as possible until I got it functioning correctly then I plan on tidying it up. I just want to get it functioning first to where I have a deeper understanding as I'm doing a lot of customization so it fits with my already written code. That being said, I'm going to try to make this post as organized and clear as possible as I really need some help. I have a news_feed.php includes file that looks like this-> <div class="col-sm-12 col-lg-8 ms-3 me-3 column2"> <form action="" method="POST"> <textarea class="form-control" name="post_text" id="text-area" placeholder="Post to your profile" rows="6" autofocus></textarea> <div class="buttons"> <input class="form-group btn btn-outline my-2 button" type="submit" name="submit_post" id="post-button" data-bs-toggle="tooltip" title="Post to your profile" data-bs-html="true" value="Post"> </div> </form> <?php //$post->getUserPosts(); ?> <div class="posts_area"></div> <img src="img/icons/loading.gif" id="loading"> </div> <!-- end newsfeed --> </div> <!-- end inner row --> </div> </div> It's all pretty straight forward. When the $post->getUserPosts() is uncommented all the posts are displayed. It's commented out right now because of the next 2 files. Next I have an ajax_load_posts.php file that looks like this -> <?php require_once($_SERVER["DOCUMENT_ROOT"] . "/qcic/assets/core/init.php"); $user = new User(); $posts = new Post(); $limit = 10; // loaded posts per call // pull userLoggedIn from ajax script $request = $_REQUEST['userLoggedIn']; $posts->getUserPosts($request, $limit); The last line in this file is why I have the $post->getUserPosts() in the previous one commented out. Next I have the following AJAX. None of this is my code and it's the code I'm trying to integrate into my own project -> <script> var userLoggedIn = '<?php echo $user->data()->username; ?>'; $(document).ready(function() { $('#loading').show(); //ajax for loading first posts $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=1&userLoggedIn=" + userLoggedIn, cache: false, success: function(data) { $('#loading').hide(); $('.posts_area').html(data); } }); $(window).scroll(function() { var height = $('.posts_area').height(); //div containing posts var scroll_top = $(this).scrollTop(); var page = $('.posts_area').find('.nextPage').val(); var noMorePosts = $('.posts_area').find('.noMorePosts').val(); if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { $('#loading').show(); var ajaxReq = $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=" + page + "&userLoggedIn=" + userLoggedIn, cache: false, success: function(response) { $('.posts_area').find('.nextPage').remove(); //removes current next page $('.posts_area').find('.noMorePosts').remove(); //removes current next page $('#loading').hide(); $('.posts_area').append(response); } }); } // end if return false; }); }); </script> Finally I have my getUserPosts() method in my Post class. The majority of this is my code but I've had to make some amendments for this particular task I'm working on. (again, please don't think I'm ignoring anyones advice, I'm not, I will change many things once my understanding is more complete and I get it functioning). -> <?php public function getUserPosts($data, $limit) { // public function getUserPosts() { //$page comes from the $_GET data in ajax script $page = $data['page']; $userLoggedIn = $this->user->username; if($page == 1) { $start = 0; } else { $start = ($page - 1) * $limit; } $table = "un_posts"; $field = "deleted"; $value = "no"; $rule = "ORDER BY id DESC"; $query = $this->_db->get($table, array($field, "=", $value), $rule); $this->_data = $query->all(); // $this->_data is an array of objects $str = ""; //html string to return if (count($this->_data) > 0) { $num_iterations = 0; # number of results checked (not necessarily posted) $count = 1; // foreach ($this->data() as $obj) { // $post_data = array( // "id" => $obj->id, // "content" => $obj->content, // "added_by" => $obj->add_by, // "date_added" => date("F d, Y H:i:s", strtotime($obj->date_added)), // "user_to" => $obj->user_to, // ); $cnt = 0; while($cnt < count($this->data())) { $post_data = array( "id" => $this->data()[$cnt]->id, "content" => $this->data()[$cnt]->content, "added_by" => $this->data()[$cnt]->add_by, "date_added" => date("F d, Y H:i:s", strtotime($this->data()[$cnt]->date_added)), "user_to" => $this->data()[$cnt]->user_to, ); //prepare user string if it's not posted to a user if ($post_data["user_to"] == "none") { $user_to = ""; } else { $user_to_obj = new User($post_data["user_to"]); $user_to_firstname = $user_to_obj->data()->firstname; $user_to_lastname = $user_to_obj->data()->lastname; $user_to = "to <a href='" . $post_data["user_to"] ."'>" . $user_to_firstname . " " . $user_to_lastname . "</a>"; } //check if poster has account closed $added_by_obj = new User($post_data["added_by"]); if ($added_by_obj->isClosed()) { continue; } if($num_iterations++ < $start) { continue; } //load 10 posts and break if($count > $limit) { break; } else { $count++; } //TODO change this for people who use username instead of real names $firstname = $added_by_obj->data()->firstname; $lastname = $added_by_obj->data()->lastname; if ($firstname && $lastname) { $name = $firstname . " " . $lastname; } else { $name = $added_by_obj->data()->username; } $profile_pic = $added_by_obj->data()->profile_pic; //timeframe $datetime_now = date("Y-m-d H:i:s"); $start_date = new DateTime($post_data["date_added"]); //time of post $end_date = new DateTime($datetime_now); // current time $interval = $start_date->diff($end_date); //difference if ($interval->y >= 1) { if ($interval == 1) { $time_message = "1 year ago"; } else { $time_message = $interval->y . " years ago"; } } elseif ($interval->m >= 1) { if ($interval->d == 0) { $days = " ago"; } elseif ($interval->d == 1) { $days = "1 day ago"; } else { $days = $interval->d . " days ago"; } if ($interval->m == 1) { $time_message = "1 month " . $days; } else { $time_message = $interval->m . " months " . $days; } } elseif ($interval->d >= 1) { if ($interval->d == 1) { $time_message = "Yesterday"; } else { $time_message = $interval->d . " days ago"; } } elseif ($interval->h >= 1) { if ($interval->h == 1) { $time_message = "An hour ago"; } else { $time_message = $interval->h . " hours ago"; } } elseif ($interval->i >= 1) { if ($interval->i == 1) { $time_message = "A minute ago"; } else { $time_message = $interval->i . " minutes ago"; } } elseif ($interval->s < 30) { if ($interval->s == 1) { $time_message = "Just now"; } else { $time_message = $interval->s . " seconds ago"; } } $str .= " <div class='status_post'> <div class='post_profile_pic'> <img src='../usernet/img/profile_pics/{$profile_pic}' width='50'> </div> <div class='posted_by'> <a href='{$post_data['added_by']}'> {$name} </a> {$user_to} &nbsp;&nbsp;&nbsp;&nbsp; {$time_message} </div> <div id='post_body'> {$post_data['content']} <br> </div> </div> <hr>"; $cnt++; } if($count > $limit) { //keeping these hidden just to store the values $str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'> <input type='hidden' class='noMorePosts' value='false'>"; } else { $str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align: centre;'> No more posts to show!</p>"; } } echo $str; } The original commented out at the top (with no parameters) is my original and corresponds to the commented out call to this method in the first file I posted. As is, this is not showing the posts only the loading.gif from the first file. I suspect it's not reading the ajax_load_post.php file correctly if at all, as that is where the new call to this method is located. I'm not sure what my actual question is other than "How do I get this working properly?". outside using AJAX for some API calls this is my first foray into using it in a more complex manner. I've tried to keep my code well commented and this post organized so as not to discourage people from responding. I'm pretty lost in the jungle right now and any compass or map any of you could provide would be appreciated. Thank you.
  6. OK, thank you all for your responses. I'm not done with this issue yet but it seems more appropriate to continue it in a new thread, which is what I'll do
  7. Ok, thanks all. I didn't realize that the false return was built into the mysqli function. I guess I thought that breaking at the end was automatic by the while loop functionality. Knowing that, it's an easy fix -> <?php $cnt = 0; while($cnt < count($this->data())) { $post_data = array( "id" => $this->data()[$cnt]->id, "content" => $this->data()[$cnt]->content, "added_by" => $this->data()[$cnt]->add_by, "date_added" => date("F d, 20y H:i:s", strtotime($this->data()[$cnt]->date_added)), "user_to" => $this->data()[$cnt]->user_to, ); Not a problem, but I had a few if statements within the loop that seemed would work best if I could use 'break' and 'continue' if certain conditions weren't met, which I couldn't with the foreach() $this->_data is a private attribute of the class. I have a separate public function data() that returns $this->_data. All's good now though, my misunderstanding was in the functionality of the mysqli function and the while loop function. You folks explained it perfectly, thanks to you all
  8. Hi, Freaks, I hope all are well. I'm trying to make a while loop and there's a common manner used that I've seen in many, many example of code -> <?php while($row = mysqli_fetch_array($data_query)) { ... } and this manner of doing it auto-stops when it's to the end of the mysqli array. Using this exact way is not compatible with the syntax that I can use as I use a database wrapper that is highly abstracted. for example, this would be the typical layout of a DB query for a user post -> <?php $table = "un_posts"; $field = "deleted"; $value = "no"; $rule = "ORDER BY id DESC"; $query = $this->_db->get($table, array($field, "=", $value), $rule); $this->_data = $query->all(); // $this->_data is an array of objects and this would be my typical way of assigning the data -> <?php foreach ($this->data() as $obj) { $post_data = array( "id" => $obj->id, "content" => $obj->content, "added_by" => $obj->add_by, "date_added" => date("F d, Y H:i:s", strtotime($obj->date_added)), "user_to" => $obj->user_to, ); for project specific reasons I'd like to change this from a foreach loop to a while loop. What I found out is that the auto-stop of the while loop using the $row = mysqli..... does not work if I do something like this -> <?php while($obj = $this->data()) { $post_data = array( "id" => $obj->id, "content" => $obj->content, "added_by" => $obj->add_by, "date_added" => date("F d, 20y H:i:s", strtotime($obj->date_added)), "user_to" => $obj->user_to, ); and it creates an infinite loop. Keeping in mind that $this->data() (I have a class method data() that returns $this->_data if anyone noticed the difference) is an array of objects why am I not getting the same result as <?php while($row = mysqli_fetch_array($data_query)) { ... } I don't understand. They're both arrays being looped through. What's the difference where mine isn't breaking the loop at the end but the mysqli array breaks the loop at the end of it?
  9. Another edit: EDIT: I've tried to do this statically and assign $profile_pic at the top of the registration.php page and I get the empty array error still. I've also taken it out of the User class and placed it as a function at the top of the registration.php page and I'm still getting the empty array error. -> <?php require_once($_SERVER["DOCUMENT_ROOT"] . "/qcic/assets/core/init.php"); $html = ""; $errors = array(); $sent = false; $js_switch = true; function assignDefaultProfilePic() { $path = "img/profile_pics/defaults/"; $files = glob($path . '*.png'); $file = array_rand($files); $f = explode('profile_pics/', $files[$file]); $profile_pic = end($f); return $profile_pic; // echo $profile_pic; } // $profile_pic = User::assignDefaultProfilePic(); and -> <?php if($validation->passed()) { $user = new User(); // $profile_pic = $user->assignDefaultProfilePic(); try { $user->create(array( "username" => Input::get("username"), "password" => Hash::make(Input::get("password")), "email" => Input::get("email"), // default profile pic functionality goes here // "profile_pic" => $profile_pic, "profile_pic" => assignDefaultProfilePic(), // "profile_pic" => $profile_pic, "group" => 2, )); I don't understand why it only works (gets the array) while logged in as an already registered user. I can't even think of anything else to try. Looking forward to your responses
  10. I couldn't edit my last post, thankfully I copied it before clicking the button: EDIT: Ok, so I was testing some things. This is in the registration form a I've edited my code slightly. And I'm trying to get it to assign the path string to the DB upon registration, but it keeps coming back as empty array when the 'register' button is clicked. which means it's happening at the array_rand() function, but if I sign in as a registered user and echo it out it prints the string. I don't understand why it's doing this. here is my edited code -> <?php public function assignDefaultProfilePic() { $path = "img/profile_pics/defaults/"; $files = glob($path . '*.png'); $file = array_rand($files); $f = explode('profile_pics/', $files[$file]); $profile_pic = end($f); return $profile_pic; // echo $profile_pic; } and here is the code at the top of my registration page about halfway down in the validation->passed if statement is where I'm building the registration array where I need to profile_pic info-> <?php require_once($_SERVER["DOCUMENT_ROOT"] . "/qcic/assets/core/init.php"); $html = ""; $errors = array(); $sent = false; $js_switch = true; // var_dump(Token::check(Input::get('token'))); if(Input::exists()) { if(Input::get("register_button")) { if(Token::check(Input::get('token'))) { $validate = new Validate(); //create requirements $validation = $validate->check($_POST, array( "username" => array( "name" => "Username", "required" => true, "min" => 2, "max" => 20, "unique" => "users" //unique to the users table ), "email" => array( "name" => "Email", "required" => true, //have to validate email, think I'll make it a public static function //"valid_email" => false ), "email2" => array( "name" => "Confirmation email", "required" => true, "matches" => "email" ), "password" => array( "name" => "Password", "required" => true, "min" => 6, ), "password2" => array( "name" => "Confirmation password", "required" => true, "matches" => "password" ) )); if($validation->passed()) { $user = new User(); // $profile_pic = $user->assignDefaultProfilePic(); try { $user->create(array( "username" => Input::get("username"), "password" => Hash::make(Input::get("password")), "email" => Input::get("email"), // default profile pic functionality goes here // "profile_pic" => $profile_pic, "profile_pic" => $user->assignDefaultProfilePic(), "group" => 2, )); $sent = true; $js_switch = true; } catch(Exception $e) { die($e->getMessage()); } } else { $errors = $validation->errors(); } } } elseif(Input::get("login_button")) { require("login.php"); } } ?> Any insight on this would be really appreciated
  11. Hi, Freaks I have this function -> <?php public function assignDefaultProfilePic() { $path = "img/profile_pics/defaults/"; $files = glob($path . '*.png'); $file = array_rand($files); return $files[$file]; // print_r($files); } and it's the weirdest thing. If I uncomment the print_r() and leave only $path and $files it prints the array of directory contents and everything seems fine. When I use it as is I get the following error-> I don't understand how it's possible, I've changed nothing else. Can someone please explain this to me?!
  12. Do you have a limited number of replies per initial comment or is it able to take an infinite amount (think like Reddit)??
  13. Hi, Psycho, I've finally gotten some smaller issues out of the way so I can start on this again. I was looking through you response and it pretty much makes sense to me except the third item (reply_id) I'm picturing comment_id as the primary key but I don't understand exactly what you're saying with the reply_id. How could it be empty or 0? If you get the time and will do you mind going into a bit more detail on this?! Thanks, I'd love to read whatever else you'd have to say about it.
  14. Haha, this is the first place that I placed the redirect and got that error message. After the error the wind completely left my sails because I couldn't figure out where else it should have gone and if it didn't go here then it called into question everything I thought I understood. Seeing it was my naive syntax error with the link string and that it works now where I had originally put the redirect gave me back some confidence. re-placing the message = True isn't a big deal. Thank you for you response
  15. Hay kicken, I've finally been able to get back to my project. I had to refresh my brain on the issues to solve the last few days and I figured a good way to do this was to return to the responses here. I'm not really clear on exactly what you mean in the line I quoted you in. If you find the time and the will would you mind breaking it down into what exactly is happening behind the scenes regarding this?! I think you mean that the previously existing data is being loaded before the new data (in this case the comment) is being inserted. But I feel, well I'm not sure how I feel, and if what I think you mean is correct then I'm not sure why it's doing that. From my perspective the very last command in the top of the display page is the one that changes $message to True, and that is functional as after 'submit' is clicked the message is shown, just not the comment or the count. I'm also not clear on where to put the redirect or exactly how to implement it. My redirect looks like this -> <?php Redirect::to("single_post.php?post_id=<?php echo $post_id; ?>&related=<?php echo $related; ?>"); I thought it should go within this if statement at the top of the display page <?php //simply increase #views per page load if($post_id && !empty($post_id)) { $post->viewCount($post_id); //comment to db if(Input::get('submit')) { // mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); if($comment->add($post_id, Input::get('comment'))) { $message = true; } } } And tried it after the statement outside of it. In all cases I've received this gut-wrenching error that I can't make sense of within the context of the redirect. I can't see why a redirect using the same URL that gets one to this page is causing this chaotic error message. So if you get the time and/or will to go into a bit more detail on this (or anyone reading this) I'd really love to read it, Thanks and have a great weekend
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.