I am creating a kind of messaging system with php and jQUERY, when you click on users profile and hit the messaging button it take us to the message page, it takes about 2sec to load previous message, so I added a code to scroll to bottom of the div class containing all message item once the ajax is loaded, to show latest messages , but the problem I am having is when I try to scroll up back I am having issues , the moment i try to scroll up due to the code i added it goes down on its own, any solution would be well appreciated.
Here is my JQ code - if there is anything else I can provide to help me solve this issue, I would do so quickly.
$(document).ready(function(){
/*post message via ajax*/
//get message
var c_id = $("#conversation_id").val();
//get new message every 2 second
setInterval(function(){
$(".display-message").load("get-message-ajax.php?c_id="+c_id , stateChange);
}, 2000);
});
function stateChange() {
var newstate = true;
if(newstate = true){
$(".conversation_history.clearfix").animate({
scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight
}, 1000)} else {
$(".conversation_history.clearfix").end();
var newstate = false;
}
}
Code from get_message-ajax.php
<?php
include 'db.php';
include 'function.php';
/*Get Message*/
if(isset($_GET['c_id'])){
$conversation_id = base64_decode($_GET['c_id']);
$querynew = "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'";
$mysqli_q_new = mysqli_query($connection, $querynew);
confirmQuery($mysqli_q_new);
if (mysqli_num_rows($mysqli_q_new) > 0 ){
while($user_real_info = mysqli_fetch_assoc($mysqli_q_new)){
$trap_user_from = $user_real_info['user_from'];
$trap_user_to = $user_real_info['user_to'];
$trap_user_message = $user_real_info['message'];
$querynew2 = "SELECT profile_image,firstname FROM `users` WHERE id='$trap_user_from'";
$mysqli_q_new2 = mysqli_query($connection, $querynew2);
confirmQuery($mysqli_q_new2);
$user_fetch = mysqli_fetch_assoc($mysqli_q_new2);
$user_form_username = $user_fetch['firstname'];
$user_form_img = $user_fetch['profile_image'];
?>
<div class='conversation_history_inner clearfix'>
<span><?php echo $user_form_username; ?> </span>
<div class='converstion_history_image img-is-responsive pull-left'>
<?php echo getUserImage($user_form_img) ?>
</div>
<div class='converstion_history_chat'>
<p><?php echo $trap_user_message; ?></p>
</div>
</div>
<?php
}
}
} else {
echo 'nth found';
}
?>
I'm assuming you only want to scroll down when it gets the first message. If so, I would suggest changing the stateChange function into this:
var scrolled = false;
function stateChange() {
if(!scrolled){
$(".conversation_history.clearfix").animate({scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight}, 1000);
scrolled = true;
}
}
This will make it only scroll down the first time it gets a new message instead of every time like it currently does.
The content is scrolling to bottom automatically because you have used setInterval function which will trigger at a constant interval of time. Use setTimeOut instead it will call only once after the specified time. Look here for more details
Related
I have about 60 landing pages that use different phone numbers on them. I am using a combination of WordPress and Advanced Custom Fields to place the phone numbers on their respective pages.
I am being asked to show a <div> based on the landing page URL that will not only show the phone number assigned to that page, but, keep showing the <div> (and phone number) regardless of what page the user navigates to on the website.
I have found little to no support on how to make the <div> remain visible throughout the entire session until the user closes the window.
I am thinking that this will somehow revolve around a cookie and Dynamic Number Insertion but I have no real progress to speak of. Should this be done using PHP or JS? Does a plugin exist that would allow for this on WordPress? I'm open to all suggestions.
Please try this code. Like #John C mentioned, WP Engine doesn't recommend Cookie nor PHP Session for the sake of performance and security. This is pure JavaScript code, and I think this will solve your problem.
Code in your Post/Page template file:
<div id="phone-number"></div>
<?php if( get_field('phone_number') ): ?>
<script type="text/javascript">
let phone_number = "<?php the_field('phone_number'); ?>";
</script>
<?php endif; ?>
Code in your theme JavaScript file:
<script type="text/javascript">
// in the case of the div data is persistent on the same site
// let storage = localStorage;
// in the case of the div data is persistent in the same tab, but not in new tab
let storage = sessionStorage;
let key = "phone_number"; // storage key
var global_phone_number = storage.getItem(key);
// check if storage data is set before
if (null === global_phone_number) {
// if not set the data on page into storage
global_phone_number = phone_number ? phone_number : '';
storage.setItem(key, global_phone_number);
}
document.getElementById('phone-number').innerHTML = global_phone_number;
</script>
You should use PHP and capture the session.
(untested code warning)
add_action('wp_footer', 'dynamic_phone_div');
function dynamic_phone_div() {
session_start;
if(isset($_SESSION['phone_div']) ? $phone_div = $_SESSION['phone_div'] :
$phone_div = '';
if($phone_div != '') {
echo '<div class="that_div_thing">';
echo $phone_div;
echo '</div>';
} else {
$_SESSION['phone_div'] = 123456789;
echo '<div class="that_div_thing">';
echo '123456789';
echo '</div>';
}
}
This is only raw logic. I am not sure where your div is (header/footer/page) - depending on where it is you should either use a hook (header/footer) or code it into a template (page/post).
The session will be destroyed after the user closes the tab/window.
I would probably do this with client side session storage. Providing all pages open in the same tab, the value will remain for the session, then be removed.
PHP code (in your functions.php file?) would be something like this:
function phone_script() {
$params = array(
'phone_number' => null, // Insert logic for current number. Can stay null if this is running on a non-landing page
'is_landing_page' => false // Change to true/false based on is current page a landing one or not
);
$params = json_encode( $params );
echo <<< EOT
<script>
let settings = $params;
document.addEventListener("DOMContentLoaded", function() {
if( settings.is_landing_page ) {
window.sessionStorage.setItem( 'phone-number', settings.phone_number );
} else {
settings.phone_number = window.sessionStorage.getItem( 'phone-number' );
}
if( settings.phone_number ) {
let div = document.createElement('div');
div.classList.add('phone-div');
// or add inline style
// div.style.cssText = 'position:fixed'; //etc
// Some logic here to actually add the number and any other content to the div
div.innerHTML = `The Phone number is: ${settings.phone_number}`;
document.body.appendChild(div);
}
});
</script>
EOT;
}
add_action( 'wp_footer', 'phone_script');
Note that the EOT; line MUST have no leading or trailing spaces.
The above is untested.
I have undercome a problem when implementing a "Show more button"
The page will initially display 5 rows of data, then on click the button will make a call to a php function through ajax and load more results, ultimately displaying them on the page. It does this very well.
The problem is that each of the divs are clickable in their own right to allow for user interaction. Before clicking the button the first 5 are clickable and work correctly, however after loading the first 10, the first 5 become unclickable and the rest work as expected.
See my code here:
HTML:
<div class="col-sm-12 col-xs-12 text-center pushDown">
<div id="initDisplay">
<?php
// Display all subjects
echo displaySubjects($limit);
?>
</div>
<div id="show_result"></div>
<button id="show_more" class="text-center pushDown btn btn-success">Show More</button>
</div>
On click of the button the following is happening:
JQuery:
<script>
$("#show_more").on("click", function() {
$("#initDisplay").fadeOut();
});
/* This bit is irrelevant for this question
$("#addBtn").on("click", function(){
addSubject();
});
*/
var stag = 5;
$("#show_more").on("click", function(){
stag+=5;
console.log(stag);
$.ajax({
dataType: "HTML",
type: "GET",
url: "../ajax/admin/loadSubjects.php?show="+stag,
success: function(result){
$("#show_result").html(result);
$("#show_result").slideDown();
}
});
var totalUsers = "<?php echo $total; ?>";
if(stag > totalUsers) {
$("#show_more").fadeOut();
}
});
</script>
My PHP page and functions are here:
<?php
include_once '../../functions/linkAll.inc.php';
$limit = filter_input(INPUT_GET, "show");
if (isset($limit)) {
echo displayUsers($limit);
} else {
header("Location: ../../dashboard");
}
function displaySubjects($limit) {
$connect = db();
$stmt = $connect->prepare("SELECT * FROM Courses LIMIT $limit");
$result = "";
if ($stmt->execute()) {
$results = $stmt->get_result();
while($row = $results->fetch_assoc()){
$id = $row['ID'];
$name = $row['Name'];
$image = $row['image'];
if($image === ""){
$image = "subjectPlaceholder.png"; // fail safe for older accounts with no images
}
$result .=
"
<div class='img-container' id='editSubject-$id'>
<img class='miniProfileImage' src='../images/subjects/$image'>
<div class='middle' id='editSubject-$id'><p class='middleText'>$name</p></div>
</div>
";
$result .= "<script>editSubjectRequest($id)</script>";
}
}
$stmt->close();
return $result;
}
The script being called through this is:
function editSubjectRequest(id) {
$("#editSubject-"+id).click(function(e) {
e.preventDefault(); // Prevent HREF
console.log("You clicked on " + id);
$("#spinner").show(); // Show spinner
$(".dashContent").html(""); // Empty content container
setTimeout(function() {
$.ajax({ // Perform Ajax function
url: "../ajax/admin/editSubjects.php?subjectID="+id,
dataType: "HTML",
type: "POST",
success: function (result) {
$("#spinner").hide();
$(".dashContent").html(result);
}
});
}, 1500); // Delay this for 1.5secs
});
}
This will then take the user to a specific page depending on the subject which they clicked on.
Your problem is duplicate ids. First five items are present on the page always. But when you load more, you are loading not new items, but all, including first five. As they are already present on the page, their duplicates are not clickable. The original items are however clickable, but they are hidden.
Here is what you need:
$("#show_more").on("click", function(){
$("#initDisplay").html("");
});
Don't just fadeOut make sure to actually delete that content.
This is the easiest way to solve your issue with minimum changes. But better option would be to rewrite your php, so it would load only new items (using WHERE id > $idOfLastItem condition).
Also you don't need that script to be attached to every div. Use common handler for all divs at once.
$("body").on("click", "div.img-container", function() {
var id = $(this).attr("id").split("-")[1];
});
When you are updating a DOM dynamically you need to bind the click event on dynamically added elements. To achieve this change your script from
$("#editSubject-"+id).click(function(e) {
To
$(document).on("click","#editSubject-"+id,function(e) {
This will bind click event on each and every div including dynamically added div.
I have this ajax request code
function hehe2(){
var a = $(".film2numb").val();
return $.ajax({
type : "GET",
url : "php/controller1.php?page=semuafilm",
data : "data="+a,
cache: false,
success: function(data){
$('.semuafilm').load('php/film.php');
},
});
}
and it requests this php code, basically it prints out HTML data from SQL
<?php
$indicator = $_SESSION['p'];
if ($indicator == 'filmbaru') {
# code...
$batas = $_SESSION['a'];
if (!$batas) {
$batas = 1;
}
if ($batas>1) {
$batas = $batas * 8;
}
include('connect.php');
$queryfilm = "select * from tb_film order by film_year desc, film_id desc limit $batas ,8";
$exec = $conn->query($queryfilm);
while ( $f = $exec->fetch_assoc()) {
$tn = str_replace(" ","-",$f['film_name']) ;
?>
<div class='col l3 m3 s6 itemovie'><div><img src="images/dum.jpg" class="lazy" data-original='http://www.bolehnonton.com/images/logo/<?php echo $f["film_logo"]; ?>' width="214" height="317"><div><div><div><p><b><?php echo $f['film_name']; ?></b></p><p>IMDB Rating</p><p><?php echo $f['film_genre']; ?></p><p class='center-align linkmov'><a class='dpinblock browntex' href='?page=movie&filmname=<?php echo $tn; ?>'>PLAY MOVIE</a></p><p class='center-align linkmov'><a class='dpinblock' href=''>SEE TRAILER</a></p></div></div></div></div></div>
<?php
}
?>
and here is the controller
<?php
session_start();
$a = $_GET['data'];
$p = $_GET['page'];
$g = $_GET['genre'];
$_SESSION['a'] = $a;
$_SESSION['p'] = $p;
$_SESSION['g'] = $g;
?>
My question is why every time I click button that binded to the hehe2() function (4-5 times, which requested a lot of images) the page get heavier as I click incrementally(laggy, slow to scroll), is there a way to make it lighter, or is there a way to not store image cache on page or clear every time I click the button that binded to hehe2() function?
I am not sure that my advice will be helpful, I will just share my experience.
First of all you should check your binding. Do you bind click trigger only once?
Sometimes function binds multiple times and it can slow down the page.
You can put code below inside function and check the console
console.log("Function called");
If everything is fine from that point and function fires only once - I would recommend you to change flow a little bit. Is it possible to avoid many clicks in a row? If it is not big deal - you can disable button on click, show loader and enable button when AJAX request is completed. This approach will prevent from making multiple requests at once at page will be faster.
I have a list of urls that I would like to open in a popup for say 10 seconds. So I click a button and it will open the first url then wait 10 seconds and play the next and so on until it's over.
I have found a few functions that I thought would work or help and I thought my logic was right and thought it should work but maybe someone with more knowledge can help me out. This is what I have:
<script type="text/javascript">
function Redirect(url) {
popupWindow = window.open(
url,'popUpWindow','height=481,width=858,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no')
}
function newPopup() {
<?php
$jsSql = mysql_query("SELECT * FROM `songs`");
while($jsRow = mysql_fetch_array($jsSql))
{?>
setTimeout('Redirect("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>")', 4000);
<?php
}
?>
}
</script>
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
?>
<script type="text/javascript">
function Redirect(url) {
window.open(url, 'popUpWindow', 'height=481,width=858,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no');
}
function newPopup() {
<?php
$stmt = $db->query("SELECT * FROM `songs`");
$songs = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($songs AS $index => $song) {
printf("setTimeout(Redirect('http://www.youtube.com/embed%s?autoplay=1'), 4000);", $song->url);
}
?>
}
// Start
newPopup();
</script>
Change
setTimeout('Redirect("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>")', 4000);
to
setTimeout(function() {
Redirect("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>")}, 4000);
would be a good start
I would do it like this:
var data = [];
var current = 0;
<?php
while($jsRow = mysql_fetch_array($jsSql))
echo "data.push($jsRow['url']);";
?>
function Redirect()
{
}
function newPopup()
{
Redirect(data[current]);
current++;
if (current < data.length)
setTimeout(function(){newPopup();}, 10*1000)
}
All you have to do is to call newPopup for the first time on some event. You mention button click.
The code also check if there are no more items to play.
The key to this issue is that after you open the popup window with the first URL, you then want to just set the window.location on the existing popup window so that it just loads a new URL. So, it would be something like this:
// globals
var songList;
function openNewPopup(url) {
return window.open(url, 'popUpWindow','height=481,width=858,left=10,top=10,
resizable=no,scrollbars=no,toolbar=no,menubar=no,
location=no,directories=no,status=no');
}
Then, for subsequent page loads into that existing popup window, you just
function setNewPopupURL(url, popup) {
popup.location = url;
}
I don't really know PHP, but you'd want to put the list of songs into a JS variable that you can later loop over:
// populate the songList
// the goal here is to do songList.push(songURL) for each song
// to add them all to the songList
<?php
$jsSql = mysql_query("SELECT * FROM `songs`");
while($jsRow = mysql_fetch_array($jsSql))
{?>
songList.push("<?php
echo "http://www.youtube.com/embed".$jsRow['url']."?autoplay=1";?>");
<?php
}
?>
And, then you can start the popup rotation by calling a function like this:
function runPopup() {
var index = 0;
var popup = openNewPopup(songList[index++]);
function next() {
setNewPopupURL(songList[index % songList.length), popup);
++index;
setTimeout(next, 10*1000);
}
setTimeout(next, 10*1000);
}
I have searched many, many topics on the Net discussing about session variables and how to get them from Javacript through Ajax. However, though I have been able to do so, this doesn't completely solve my problem.
Objective
To provide online inventory management online.
Constraints
Only authenticated users can manage the online inventory
Inventory management controls are hidden from an unauthenticated user
Each sections must be independently informed of the authentication in order to show/hide their controls accordingly
Code Samples
authenticate.php
project.js
index.php
atv.php
atv-inventory-list.php
sectionhandler.php
index.php
<?php session_start(); ?>
<html>
...
<div id="newAtvDialog" title="Input information on the new ATV">
<form id="newAtvAjaxForm" action="addNewAtv.php" method="post">
...
</form>
</div>
<div id="section">
<$php echo file_get_contents("inventory-sections.html"); ?>
</div>
...
</html>
authenticate.php
<?php
require_once "data/data_access.php";
$userName = "";
$password = "";
if (isset($_REQUEST["userName"])) $userName = $_REQUEST["userName"];
if (isset($_REQUEST["password"])) $password = $_REQUEST["password"];
$isAuthentic = isAuthenticUser($userName, $password);
$_SESSION["isAuthentic"] = $isAuthentic;
echo $isAuthentic;
// I try to use the below-written function where ever I need to show/hide elements.
function isCurrentUserAuthenticated() {
return isset($_SESSION["isAuthentic"]) && $_SESSION["isAuthentic"];
}
?>
project.js
$(document).ready(function() {
$("#newAtvDialog").dialog({
autoOpen: false,
closeOnEscape: true,
modal: true,
width: 1000
});
$("#newAtvAjaxForm").ajaxForm(function(data) {
$("#newAtvDialog").dialog("close");
$("#section").load("sectionhandler.php?section=atv&type=-1&make=0&year=0&category=0", function(event) { $("button").button(); });
});
});
atv.php
<div id="newAtvButton"> <!-- This DIV is to be hidden when not authenticated -->
<button id="addNewAtvButton">Add New ATV</div>
</div>
<div id="criterion">
...
</div>
<div id="atv-inventory">
<?php include ('atv-inventory-list.php'); ?>
</div>
atv-inventory-list.php
<?php
$type = -1;
$make = 0;
$year = 0;
$category = 0;
if (isset($_REQUEST["type"])) $type = $_REQUEST["type"];
...
$atvs = getAllAtvs($type, $make, $year, $category);
foreach ($atvs as $value=>$atv):
?>
<div class="inventory-item">
<img src="<?php echo utf8_decode($atv->getPathToImage())">
<div class="item-title">
...
</div>
<div id="commands">
<!-- This is the way I have tried so far, and it doesn't seem to work properly. -->
<button id="removeAtvButton"
class="<?php echo isCurrentUserAuthenticated() ? 'show' : 'hide'; ?>">
Remove ATV
</button>
</div>
</div>
sectionhandler.php
$section = "";
if (isset($_REQUEST["section"])) $section = $_REQUEST["section"];
$type = -1;
$make = 0;
$year = 0;
$category = 0;
// getting values from $_REQUEST[]
$activatedSection = "";
switch($section) {
case "atv": $activatedSection = "atv.php";
...
}
$file = $url.raw_url_encore($activatedSection);
include $file;
Supplementary thoughts
I thought of setting a boolean session variable which would expire after about 20 minutes of inactivity from the user, forcing him to log in again.
I know I shan't use passwords stored in the database. This is the first step of the authentication within this site which I shall put online pretty soon, as the client is going to ask for delivery any time soon. Encrypted passwords will be the next step. But first, I need the show/hide feature to work properly.
I have also thought about cookies, and being quite new to web development, I ain't quite sure what would be the best approach. As far as I'm concerned, the simplest the best, as long as it implies a minimum of security. This is not the NASA site after all! ;-)
Thanks everyone for your inputs! =)
It's an idea, but you can work on/from it;
actionURL is a php file where you can check if the user is logged in with a valid session.
ajaxSession function returns true or false if the user is logged.
Then you can call this function every X seconds/minutes to control if the session still going.
window.setInterval(function(){
// call your function here
if(ajaxSession(actionUrl)){
//return true, user logged, append/show protected divs.
}else{
//return false, remove/hide protected divs and ask user to log.
}
}, 5000); //every 5 seconds.
ajaxSession function:
function ajaxSession(actionUrl) {
var sessionOK= false;
$.ajax({
async: false,
url: actionUrl,
success: function(msg) {
// check the return call from the php file.
if(msg== 'OK'){
sessionOK = true;
}else{
sessionOk = false;
}
}});
return sessionOK;
}
EDIT
I will add an example code for the actionUrl, that will return if the session is isset or not to the ajaxSession function:
<?php
session_start();
// $_SESSION['reg'] is true when the user is logged in.
if($_SESSION['reg'] == true){
echo 'OK';
}else{
echo 'NO';
}
?>
Remember to check in the ajaxSession function the result of the Ajax call. If it's Ok, then sessionOk = true, if not, sessionOk = false.