jQuery PHP Chat user is typing feature - php

Im use jquery for display someone is typeing.
Its ok everything work but i want everyone can see that and i cant think about something any help ?
var textarea = $('#input');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970
var typingDelayMillis = 1500; // how long user can "think about his spelling" before we show "No one is typing -blank space." message
function refreshTypingStatus() {
if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
typingStatus.html('');
} else {
typingStatus.html('<div id="new"><div class="comment" style="display:inline;"><div class="user_name"> <b><font color="white"><?php echo $pernome?> <br> <center> <b style="font-size:9px;"> <?php echo $datenow?> </b> </center></font></b></div></div> <div class="comment" style="display:inline; position:relative; font-size:14px; bottom:6px; color:#ffffff; margin-bottom:2px;">מקליד...</div></div>');
}
}
function updateLastTypedTime() {
lastTypedTime = new Date();
}
setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);
Thanks!!

Related

How to pull data from a complicated API using AJAX and display on a .php page

Right now, the website I'm helping with is purely php, html, css, and some javascript.
I use the php to pull the data off of the Web-API and post it to the webpage.
e.g.:
$pool = json_decode(file_get_contents("http://api.link:port/api/v1/Pool-Avian/"), false);
//Removed API link since I don't have the owner's permission for specifics at this time.
<table class="table table-sm table-borderless table-striped mt-md-0 mt-3">
<tbody>
<tr>
<th>Block Reward:</th>
<td id="lastBlockReward">~2475 AVN</td>
</tr>
<tr>
<th>Blockchain Height:</th>
<td>
<?php echo $pool->body->primary->network->height; ?>
</td>
</tr>
<tr>
<th>Network Hashrate</th>
<td>
<?php echo hashRateCalculator($pool->body->primary->network->hashrate); ?>
</td>
</tr>
<tr>
<th>Network Difficulty</th>
<td>
<?php echo hashRateCalculator($pool->body->primary->network->difficulty); ?>
</td>
</tr>
<tr>
<th>Blocks Found By Pool</th>
<td>
<?php echo $pool->body->primary->blocks->valid; ?>
</td>
</tr>
</tbody>
</table>
</div>
The API is like this:
{"version":"0.0.3","statusCode":200,"headers":{"Access-Control-Allow-Headers":"Content-Type,
Access-Control-Allow-Headers, Access-Control-Allow-Origin,
Access-Control-Allow-Methods","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Content-Type":"application/json"},"body":{"primary":{"config":{"coin":"Avian","symbol":"AVN","algorithm":"x16rt","paymentInterval":21600,"minPayment":0.01,"recipientFee":0.01},"blocks":{"valid":83,"invalid":0},"shares":{"valid":20734,"stale":124,"invalid":0},"hashrate":{"shared":68131817.9050706,"solo":0},"network":{"difficulty":738.1659173695874,"hashrate":116186636292.9936,"height":541555},"payments":{"last":1647460164235,"next":1647460254235,"total":198724.56746191},"status":{"effort":61.25198558663565,"luck":{"luck1":7.93,"luck10":64.47,"luck100":89.27},"miners":3,"workers":3}},"auxiliary":{"config":{"coin":"","symbol":"","algorithm":"","paymentInterval":0,"minPayment":0,"recipientFee":0},"blocks":{"valid":0,"invalid":0},"shares":{"valid":0,"stale":0,"invalid":0},"hashrate":{"shared":0,"solo":0},"network":{"difficulty":0,"hashrate":0,"height":0},"payments":{"last":0,"next":0,"total":0},"status":{"effort":0,"luck":{"luck1":0,"luck10":0,"luck100":0},"miners":0,"workers":0}}}}
I reviewed some websites and tutorials for how to do this, but I can't seem to get them to work...
Right now, my test page has this:
<script>
miner = 0;
function updateData() { //Obtain data from API and push to website//
miner = miner + 1;
document.getElementById("minerBottom").innerHTML = miner;
}
window.onload = function () {
webHandler();
};
function webHandler() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.link:port/api/v1/Pool-Avian/", true);
//again - API redacted//
xhr.onload = function () {
if (this.status === 200) {
// Changing string data into JSON Object
obj = JSON.parse(this.responseText);
// Getting the ul element
let list = document.getElementById("list");
str = "";
for (key in obj.data) {
str +=
`<li>${obj.data[key].employee_name}</li>`;
}
list.innerHTML = str;
} else {
console.log("File not found");
}
};
xhr.send();
}
</script>
and the test elements are:
<div class="totalBox">
<div class="totalValue" id="minerTop">
Miners
</div>
<div class="totalValue" id="minerBottom">
</div>
</div>
<div class="totalBox">
<div class="totalValue" id="workerTop">
Workers
</div>
<div class="totalValue" id="workerBottom">
0
</div>
</div>
<div class="totalBox">
<div class="totalValue" id="blockTop">
Blocks
</div>
<div class="totalValue" id="blockBottom">
0
</div>
</div>
It's losing me at the "Getting the ul element" part - I'm not sure what it's trying to do, or how I'd morph this into what I need it to do.
What I want it to do is find the pair I'm looking for (e.g. body->primary->status->miners) and display it in the appropriate <div>
Based on answer - updated script to:
function webHandler() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.link:port/api/v1/Pool-Avian/", true);
//again - API redacted//
xhr.onload = function () {
if (this.status === 200) {
// Changing string data into JSON Object
obj = JSON.parse(this.responseText);
// get "miners" from API response.
// This does not validate if the value is actually in the object!
let miners = obj.body.primary.status.miners;
// get DOM element by id
let minersElement = document.getElementById('minerBottom');
// set value of miners as text in DOM
minersElement.innerText = miners;
} else {
} else {
console.log("File not found");
}
}
};
xhr.send();
}
No display in those div are happening
For miners, here's an example in your test page script.
if (this.status === 200) {
// Changing string data into JSON Object
obj = JSON.parse(this.responseText);
// get "miners" from API response.
// This does not validate if the value is actually in the object!
let miners = obj.body.primary.status.miners;
// get DOM element by id
let minersElement = document.getElementById('minerBottom');
// set value of miners as text in DOM
minersElement.innerText = miners;
} else {
console.log("File not found");
}
Please note, that this does not include any sanitizing checks or validation if response from API is valid.

Lazy Load for CSS Images

I have the following lazy load function which works for <img>.
<script>
document.addEventListener("DOMContentLoaded", function() {
var lazyloadImages;
if ("IntersectionObserver" in window) {
lazyloadImages = document.querySelectorAll(".lazy");
var imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
image.classList.remove("lazy");
imageObserver.unobserve(image);
}
});
});
lazyloadImages.forEach(function(image) {
imageObserver.observe(image);
});
} else {
var lazyloadThrottleTimeout;
lazyloadImages = document.querySelectorAll(".lazy");
function lazyload () {
if(lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function() {
var scrollTop = window.pageYOffset;
lazyloadImages.forEach(function(img) {
if(img.offsetTop < (window.innerHeight + scrollTop)) {
img.src = img.dataset.src;
img.classList.remove('lazy');
}
});
if(lazyloadImages.length == 0) {
document.removeEventListener("scroll", lazyload);
window.removeEventListener("resize", lazyload);
window.removeEventListener("orientationChange", lazyload);
}
}, 20);
}
document.addEventListener("scroll", lazyload);
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);
}
})
</script>
The function isn't mine and I need to know how to modify it to work for the next example which load images from CSS:
<div class="col-md-2 col-sm-3 col-xs-4 photo" style="padding: 2.5px">
<span onclick="window.location.href=\''.$link.'\';"
class="thumbnail"
role="img"
style="background-image: url(\''.$image.'\'); cursor: pointer; margin: 0; margin-top: 5px;"
aria-label="' . $row["topic_title"] . '"
title="'.$row['topic_title'].'">
</span>
<center>
<p class="name" style="margin 0 2px; color: white; margin-top: 5px;">
' . $title . '
</p>
</center>
</div>
On a page with 24 gifs, the page loads relatively slow and I'd like to change that.
I could load the images as normal using <img>, but I want the page to be more dynamic because using span I have different temathic.
Here is how I managed to do the script and it works correctly.
Hope someone will find it useful.
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
var imageUrl = "url" + "(" + "'" + image.src + "')";
entry.target.style.backgroundImage = imageUrl;
image.classList.remove("lazy");
imageObserver.unobserve(image);
}
On a page with 24 gifs, the page loads relatively slow and I'd like to
change that.
Images in general are really heavy on websites. That's most likely whats slowing the site down. If your website needs that many GIFs I would firstly look at compression techniques. Search for GIF to WebP converters and file compressors (ImageAlpha, ImageOptim, Handbrake to name a few).
Good luck!

Show / hide php mysql results with loader

I have MySQL database results.
I want to show 3 rows and then hide rest.
When the user clicks to load more data then to appear all rows.
The problem is when I click show more, then only one more row appears.
<?php
$query_brands = mysql_query("SELECT distinct pd_filter1 from tbl_brands2 WHERE pd_code in (select pd_code from tbl_product where cat_id='2')") or die(mysql_error());
$count_brands = mysql_num_rows($query_brands);
if($count_brands > 0) {
while($fetch_brands = mysql_fetch_array($query_brands)) {
$record_brands[] = $fetch_brands;
}
}
$i_brands=0;
foreach($record_brands as $records_brands) {
?>
<table border="1" width="215" style="border-collapse: collapse; border-spacing: 0;" bgcolor="#eeeff0">
<tr>
<td>
<?php
$i_brands = $i_brands + 1;
if ($i_brands > 3)
{
?>
<div id="myDIV_Filter1_1" style="display:none";>
<?php
}
}
?>
<div id="myDIV_Filter1_2">
<span class="class22">
show more...
</span>
</div>
<div id="myDIV_Filter1_3" style="display:none";>
<span class="class22">
show less...
</span>
</div>
</td>
</tr>
</table>
JavaScript
function myFunction() {
var x_filter1_1 = document.getElementById("myDIV_Filter1_1");
var x_filter1_2 = document.getElementById("myDIV_Filter1_2");
var x_filter1_3 = document.getElementById("myDIV_Filter1_3");
if (x_filter1_1.style.display === "none") {
x_filter1_1.style.display = "block";
x_filter1_2.style.display = "none";
x_filter1_3.style.display = "block";
} else {
x_filter1_1.style.display = "none";
x_filter1_2.style.display = "block";
x_filter1_3.style.display = "none";
}
}
You have some errors on your code:
1) Try not to use return the way you are using right now in code lines like this one:
show more...
You can use it better like it's explained here
2) You have all your divs of the code example in display none, the user will never see the information in those divs because you don't have any code to start showing some of them. In the same line you put a ";" after the style but it must be inside the style. This line has an error:
<div id="myDIV_Filter1_3" style="display:none";>
It must be this way:
<div id="myDIV_Filter1_3" style="display:none;">
The "show-hide" logic on your javascript function myFunction has an error because your div id="myDIV_Filter1_1" contains the other 2 div you have on your code example so you can't hide this particular div because you will lose the "show" or "hide" of the other 2 divs. That way it'll never show you the other 3 rows you wanted to see. I fixed all the errors you can check the code on my snippet here:
function myFunction() {
var x_filter1_1 = document.getElementById("myDIV_Filter1_1");
var x_filter1_2 = document.getElementById("myDIV_Filter1_2");
var x_filter1_3 = document.getElementById("myDIV_Filter1_3");
if (x_filter1_3.style.display === "none") {
x_filter1_1.style.display = "block";
x_filter1_2.style.display = "none";
x_filter1_3.style.display = "block";
} else {
x_filter1_1.style.display = "block";
x_filter1_2.style.display = "block";
x_filter1_3.style.display = "none";
}
}
<?php
$query_brands = mysql_query("SELECT distinct pd_filter1 from tbl_brands2 WHERE pd_code in (select pd_code from tbl_product where cat_id='2')") or die(mysql_error());
$count_brands = mysql_num_rows($query_brands);
if($count_brands > 0) {
while($fetch_brands = mysql_fetch_array($query_brands)) {
$record_brands[] = $fetch_brands;
}
}
$i_brands=0;
foreach($record_brands as $records_brands) {
?>
<table border="1" width="215" style="border-collapse: collapse; border-spacing: 0;" bgcolor="#eeeff0">
<tr>
<td>
<?php
$i_brands = $i_brands + 1;
if ($i_brands > 3)
{
?>
<div id="myDIV_Filter1_1">
<?php
}
}
?>
<div id="myDIV_Filter1_2" >
<span class="class22">
show more...
</span>
</div>
<div id="myDIV_Filter1_3" style="display:none">
<span class="class22">
show less...
</span>
</div>
</td>
</tr>
</table>
Hope it helps!

How to Refresh (Update) an HTML Page For New Data After the Submit Button is Pressed

I have an HTML form that is split into three major components. The top portion is essentially a header for displaying a magazine name. This information does not change.
The middle portion is a table developed through a MySQL query for displaying the story information as a table of contents after it is entered in the bottom portion, which is a data entry screen.
The bottom portion, is a data entry screen for entering the information concerning each story contained in the magazine issue.
After entering the data and pressing the submit button in the bottom portion, the middle portion should be updated through the MySQL query to reflect the newly entered story. That was not happening.
Note: The code previously associated with this question has been removed for purposes of clarity. The solution was associated with how the various forms were called. My thanks to Sulthan Allaudeen for providing potential solutions. Currently, I am not familiar with utilizing jquery-ajax. Eventually I will need to learn.
As the OP wanted to know how do the jquery and ajax call
Step 1 :
Recognize the Input
Have a button with a class trigger
$(".trigger").click(function()
{
//your ajax call here
}
Step 2 :
Trigger your ajax call
$.ajax({
type: "POST",
url: "yourpage.php",
data: dataString,
cache: false,
success: function(html)
{
//your action
}
});
Step 3 :
Inside your success function show the result
$("#YourResultDiv").html(data);
For that you should create a div named as YourResultDiv
Note :
Inside your yourpage.php You should just print the table and it will be displayed as the output
Here's a brief example of displaying the results of submitting a form without leaving the current page. Form submission is done with the help of Ajax.
Each form has it's own button for submission, hence the loop over matching elements in onDocLoaded.
1. blank.php form is submitted to this script
<?php
echo "-------------------------------<br>";
echo " G E T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_GET ); echo "<br>";
echo "-------------------------------<br>";
echo " P O S T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_POST ); echo "<br>";
echo "<hr>";
if (count($_FILES) > 0)
{
var_dump($_FILES);
echo "<hr>";
}
?>
2. blank.html Contains 2 forms, shows the result of submitting either of them to the above script.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}
function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var reader = new FileReader();reader.onload = loadedCallback;reader.readAsDataURL( fileObj );}
function myAjaxGet(url, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("GET", url, true);
ajax.send();
}
function myAjaxPost(url, phpPostVarName, data, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(phpPostVarName+"=" + encodeURI(data) );
}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
forEachNode( allByClass('goBtn'), function(elem){elem.addEventListener('click', onGoBtnClicked, false);} );
}
function onGoBtnClicked(evt)
{
evt.preventDefault();
var thisElem = this;
var thisForm = thisElem.parentNode;
myAjaxPostForm('blank.php', thisForm, onPostSuccess, onPostFailed);
function onPostSuccess(ajax)
{
byId('tgt').innerHTML = ajax.responseText;
}
function onPostFailed(ajax)
{
//byId('tgt').innerHTML = ajax.responseText;
alert("POST FAILED!!!!");
}
return false;
}
</script>
<style>
#page
{
display: inline-block;
border: solid 1px gray;
background-color: rgba(0,0,0,0.2);
border-radius: 6px;
}
.controls, .tabDiv
{
margin: 8px;
border: solid 1px gray;
border-radius: 6px;
}
.tabDiv
{
overflow-y: hidden;
min-width: 250px;
background-color: white;
border-radius: 6px;
}
.tabDiv > div
{
padding: 8px;
}
</style>
</head>
<body>
<div id='page'>
<div class='tabDiv' id='tabDiv1'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Name: </label><input name='nameInput'/><br>
<label>Age: </label><input type='number' name='ageInput'/><br>
<input type='file' name='fileInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<div class='tabDiv' id='tabDiv2'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Email: </label><input type='email' name='emailInput'/><br>
<label>Eye colour: </label><input name='eyeColourInput'/><br>
<label>Read and agreed to conditions and terms: </label><input type='checkbox' name='termsAcceptedInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<!-- <hr> -->
<div class='tabDiv'>
<div id='tgt'></div>
</div>
</div>
</body>
</html>
The solution to refreshing the form to display the addition of new data was to re-call it through the following line: "include("new_stories.inc.php");". This line is imediately executed just after the MySQL insert code in the data entry section of the form.
The middle section of the form "new_stories.inc.php" (the table of contents) queries the MySQL data base to retrieve the story information related to the current magazine issue. Re-calling the form is equivalent to a re-query.

Fancybox only works after second click

So I have a table where each cell is a name of a game and when you click it it needs to show in a fancybox the results of the user which clicked the cell (I use table Indexes to get the GameID and the Session variable to get userID) which will be used to load the results from a second PHP page.
If I click on a cell for the first time the fancybox will not display anything and after I close fancybox and click on any cell again it works fine. Am I doing something wrong?
This is the whole javascript:
$(".jogos").fancybox({
'hideOnContentClick': true,
'onComplete':function(element)
{
var gameIdx = $(element).index();
var cateIdx = $(element).parent().parent().index();
var gameIdxPHP;
var catIdxPHP;
var gameID;
var userId = '<?php echo $_SESSION['userID']; ?>'
<?php
for ($i=1; $i<= count($categoryArray);$i++)
{
for ($j=1; $j<=count($categoryArray[$i-1]->gamelist);$j++)
{
?>
catIdxPHP = '<?php echo $i ?>' -1;
gameIdxPHP = '<?php echo $j ?>' -1;
if (catIdxPHP == cateIdx && gameIdxPHP == gameIdx)
{
gameID = '<?php echo $categoryArray[$i-1]->gamelist[$j-1]->GameID; ?>';
$("#graphic").load("backoffice/resUserNivel2short.php", {userId:userId,gameID:gameID}, function(){ });
}
<?php
}
}
?>
}
});
HTML
<div style="display:none">
<div id="data">
<div id="graphic">
</div>
</div>
</div>
Sample code of the link
<a href="#data" class="jogos" id="cat<?php echo $i; ?>jogo<?php echo $j; ?>" >
You have display:none on the parent of your fancybox therefor the grafic isnt displayed.
The Grafic element isn't inside the dom yet if you use display:none initially. Try to use clip: rect instead as a class and add/remove that class using the fancybox callbacks.
Try this code:
$('.jogos').fancybox({
'onStart': function() {
$("#data").removeClass('hidden');
},
'onClosed': function() {
$("#data").addClass('hidden');
}
});
CSS:
.hidden {
clip: rect(1px 1px 1px 1px);
position: absolute;
)}
HTML:
<div>
<div id="data" class="hidden">
<div id="graphic">
</div>
</div>
</div>

Categories