I'm making a chatbox for my website but when I try to get a data- value my result is undefined. My javascript calls the AJAX to my fetchChat.php as so...
var myVar = setInterval(function () {refreshChat()}, 5000);
function refreshChat() {
var lastItem = 0;
lastItem = $(".chatmessage:last-child").data('value');
if (typeof lastItem === 'undefined')
{
alert("undefined");
lastItem = 0;
}
$.post("outputPages/fetchChat.php", {'li':lastItem}, function(response)
{
$(".messagefeed").append(response);
});
}
And my PHP in fetchChat is:
<?PHP
require "../pages/connect.php";
$li = $_POST;
$li = implode($li);
$fetch = "SELECT * FROM chat WHERE messageID >= '$li' ORDER BY messageID ";
if ($result = $mysqli->query($fetch)) {
while ($row = $result->fetch_array()) {
$ID = $row['messageID'];
$date = $row['messageDate'];
$persona = $row['messagePersona'];
$message = htmlspecialchars($row['message'], ENT_QUOTES);
echo "<p class='chatmessage' data-value='$ID'>$date $persona: $message</p>";
}
}
?>
So basically I use the data-value of the last message to get all messages greater than the last message. But whenever I echo lastItem in javascript it returns undefined. Any help is really appreciated! This is my own idea and Im trying to see what I can do with my school knowledge so far.
Fixed! I have to change my lastItem to $(".chatmessage:last-child").attr('data-value');
Thank you Roumelis for the help!
Related
I am trying to capture a value that is calculated on a PHP page called "classes_day.php" at the same time as I pass a value per GET, "? Day = YYYY-mm-dd" to it. How do I do this with JS or JQuery?
<?php
// aulas_dia.php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT * FROM `task` WHERE `dia` LIKE ".$data."";
$result = mysqli_query($link,$query);
$soma = 0;
while ($row = mysqli_fetch_assoc($result)) {
$soma = $soma+$row['duration'];
}
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
?>
I already tried using an iframe and contentwindow, but iframe gets the value and the contentwindow is empty (weird isn't it?).
Following Barmar's tip, I'm using $ .get, but I don't know why this loop is not working, can anyone help me?
for (i = 0; i < num_days; i++) {
x = (first_day+i)%7;
y = (first_day+i-x)/7;
h_dia(String(y)+String(x),i+1);
data_c = ano+"-"+mes+"-"+String(i+1);
$.get("aulas_dia.php?data="+data_c, function(data){
console.log(String(y)+String(x)+" - "+data_c+" - "+data);
set_aulas_fun(String(y)+String(x),data);
});
}
Use $.get() to send an AJAX request.
$.get("classes_day.php?data=YYYY-MM-DD", function(response) {
console.log(response);
});
BTW, you can add up all the durations in the SQL query instead of using a PHP loop. And you should use a prepared statement to prevent SQL injection.
<?php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT SUM(duration) AS total FROM `task` WHERE `dia` LIKE ?";
$stmt = $link->prepare($query);
$stmt->bind_param("s", $data);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$soma = $row['total'];
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
I would think this is simple but cannot figure it out for the life of me.. I want to refresh a div without refreshing everything.. I have a timer on each image that counts down from 24 hrs to 0 then disappears.. it all works but I cant seem to just refresh the timer div..
My php -
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$path = $row['path'];
$user = $row['user'];
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer <= 0){
}else{
echo '<img id="pic" src="/v2/uploads/'.$path.'"/>';
echo '<div id="user">#'.$user.'</div>';
echo '<div id="timer">'.$timer.' </div>';
}
}
}
I would like to refresh just the timer at 1 second intervals not the images.. I know I can use ajax to call it from an external file that loads all the content also as far as I know..Still new at this. *side not this is chopped up code for the example not all of it.
As per my comment, you could do something like this:
Add class "timer" to your #timer element (if you have more than one #timer element, use different ID for each element).
Create php script which returns new $timer whenever it's called:
ajax-timer.php
<?php
/* include file where $conn is defined */
$response = array();
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer > 0) {
//Add just timer to response array
$response[] = $timer;
}
}
}
//Return json response and handle it later in ajax:
echo json_encode(array(
'result'=>empty($response) ? 0 : 1,
'data'=>$response));
die();
Request data from ajax-timer.php with $.ajax and populate data when response is received:
timer-update.js
var ajaxTimerThread = 0;
var ajaxTimerRunning = false;
function ajaxTimerRun() {
//Prevent running function more than once at a time.
if(ajaxTimerRunning)
return;
ajaxTimerRunning = true;
$.post('ajax-timer.php', {}, function (response) {
ajaxTimerRunning = false;
try {
//Try to parse JSON response
response = $.parseJSON(response);
if (response.result == 1) {
//We got timer data in response.data.
for(var i = 0; i < response.data.length; i++) {
var $timer = $('.timer').eq(i);
if($timer.length) {
$timer.html(response.data[i]);
}
}
}
else {
//Request was successful, but there's no timer data found.
//do nothing
}
//Run again
ajaxTimerThread = setTimeout(ajaxTimerRun, 1000); //every second
}
catch (ex) {
//Could not parse JSON? Something's wrong:
console.log(ex);
}
});
}
$(document).ready(function() {
// Start update on page load.
ajaxTimerRun();
})
Toss your existing php code into a separate .php file
Then use a jquery method called load() to load that php file into your div.
$(document).ready(function() {
$("#div_ID_you_want_to_load_into").load("your_php_file.php");
var pollFrequency = function() {
if (document.hidden) {
return;
}
$("#div_ID_you_want_to_load_into").load('your_php_file.php?randval='+ Math.random());
};
setInterval(pollFrequency,18000); // microseconds, so this would be every 18 seconds
});
Now, within this code above is something is not needed, but can be helpful, and that is the if (document.hidden) {return;} which is basically a command to the browser that if the browser tab is not in-focus do not fire off the setInterval poll.
Also a good idea to keep in the randval= math stuff, just to make sure there is no caching.
I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}
Good Morning, I have Written a Dashboard for work written in PHP and Javascript. It pulls Data from our database and shows events in Divs with a class of Dash, Showing a Variable of $nextupdate, I need to write some Js that will compare the DateTime Now and if the $nextupdate variable time is past then i need to change the Div Class to .overdue, I am struggling to figure out how would be the best way to solve this
any help would be much appreciated
Regards
Steve
Try this :
$nextupdate; // got from the database
$now = date();
$divClass = "";
if(strtotime($now) > strtotime($nextupdate) ){
$divClass="overdue";
}else{
$divClass="whatever";
}
and then :
<div class="<?php echo $divClass; ?>"></div>
That works Great for changing the Div colour to red when overdue, Although i didnt explain that i have Multiple Divs...
Here is my Code for the Div
//Gather all Posted HPi tickets raised
$sql = "Select *
From hpi_calls
where status!='Closed'
and (Priority='P1' or Priority='M1')
order by NextUpdate Asc";
$result = $conn->query($sql);
$statuslist = "";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SR = $row["SR"];
$Priority = $row["Priority"];
$Customer = $row["Customer"];
$BDescription = $row["BDescription"];
$Team = $row["Team"];
$Engineer = $row["Engineer"];
$OpenTime = $row["OpenTime"];
$Status = $row["Status"];
$LastUpdate = $row["LastUpdate"];
$NextUpdate = $row["NextUpdate"];
$Owner = $row["Owner"];
$FDescription = $row["FDescription"];
$ASites = $row["ASites"];
$LoggingTeam = $row["LoggingTeam"];
$OwningTeam = $row["OwningTeam"];
$FUpdate = $row["FUpdate"];
$Supplier = $row["Supplier"];
$NextUpdate;
$now = date("Y-m-d H:i");
$divClass = "";
if(strtotime($now) > strtotime($NextUpdate) ){
$divClass="Overdue";
}else{
$divClass="Dash";
}
$statuslist .= '<div id="status_'.$SR.'" class=" '.$divClass.'"><h2>'
.$SR.'</h2><h2>'.$Customer.'</h2><h2>'.$Priority.'</h2> - '.$Status.'<br><h2>Next Update Due:<br>'.$NextUpdate.'</h2></div>';
}
}
The above is the Complete code for selecting from the DB and posting to the Divs
Regards
Steve
PHP:
$ports = $Db->query('SELECT port FROM servers');
Javascript:
$("#port").on('keyup', function(){
var port = $("#port").val();
var portlist = <?php print(json_encode($ports)); ?>;
if(jQuery.inArray(port, portlist[port])!==-1)
{
$("#result").removeClass("label-success");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-danger");
$("#result").html("Port belegt!");
}
else
{
$("#result").removeClass("label-danger");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-success");
$("#result").html("Port Frei!");
}
})
Why is this not working?
The array contains 1234 and 7777.
So if I type 7777 into the html input field (#port) it should do the first action (if true)
But it always goes into the else action.
you need to cast integers in array to string by quoting and remove [port]
here is a working example of your code
http://jsfiddle.net/4X68y/
var portlist = ["1234","777"];
if(jQuery.inArray(port, portlist)!==-1)
jQuery inArray accepts array as second parameter - not specific key.
Try this:
$("#port").on('keyup', function(){
var port = $(this).val();
var portlist = <?php print(json_encode($ports)); ?>;
if(jQuery.inArray(port, portlist)!==-1)
{
$("#result").removeClass("label-success");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-danger");
$("#result").html("Port belegt!");
}
else
{
$("#result").removeClass("label-danger");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-success");
$("#result").html("Port Frei!");
}
})
--EDIT--
The following works for me (if the portlist is array not json object. If it isnt maybe it's a good idea to just loop the results and create the array old fashioned way like below)
PHP:
<?php
$q = $db->query("SELECT port FROM ports");
$ports = array();
while($$row = $result->fetch_assoc()){
$ports[] = $row['port'];
}
?>
JS CODE:
$("#port").on('keyup', function(){
var port = parseInt($(this).val());
var portlist = <?php print(json_encode($ports)); ?>;
if(jQuery.inArray(port, portlist)===-1)
{
$("#result").removeClass("label-success");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-danger");
$("#result").html("Port belegt!");
}
else
{
$("#result").removeClass("label-danger");
$("#result").removeClass("label-warning");
$("#result").addClass("label label-success");
$("#result").html("Port Frei!");
}
})