Hello I have dynamic videos which I tried to get the current video time but I seem to be getting undefined which i don't know why. I fire a function using on time update javascript event, however when i alert this var ok=$(e).attr('id'); i get the videos id but i dont know why when i try to get video current time i get undefined as value, these is my code dont know where i am getting it wrong.
<script type='text/javascript'>
function men(e){
var ok = $(e).attr('id');
var ol = $(e).attr('id');
// alert(ol[0].currentTime); --- GIVES ME UNDEFINED
$.ajax({
type : 'POST',
url : 'updatetime.php',
data : {ok: ok, om: om},
success : function(r)
{
}
});
}
</script>
<?php
$tl="channel";
$ooa="playing";
$played="played";
$timeline = mysqli_query($con, "SELECT * FROM plays WHERE streamers_type ='$tl' AND played !='$played' GROUP BY streamers_id ORDER BY id ASC") or die ();
while($row = mysqli_fetch_array($timeline)) {
$id = $row['id'];
$file1 = $row['file1'];
$video_name = $row['video_name'];
$video_type = $row['video_type'];
?>
<video class="uopi spinal" id="<?php echo $id ?>" style="height:180px; width:100%!important;" autoplay muted onended="run(this)" ontimeupdate="men(this)"><source src="plays/<?php echo $file1 ?>" type="<?php echo $video_type ?>"></video>
<?php } ?>
What you're doing is
var ol = $(e).attr('id');
ol[0].currentTime;
But .attr('id') returns a string, the ID of the element, which clearly doesn't have a currentTime property.
Try doing
$(e)[0].currentTime
instead
Related
Im trying to make my Webpage do an action (in this case play a sound) on the event of the highest ID (auto_increment) in my SQL table increasing, which happens when a new user is registered. E.g. : 3 users registered, highest ID = 3. When a new user registers, highest ID = 4. Webpage echos/plays sound if this happens.
The Js and PHP, respectively:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['firstName'];
echo $row['lastName'];
echo $row['inOrOut'] . '<br>';
$numId = $row['ID'] . '<br>';
echo $numId;
}
$value = 1;
$value = $numId;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
}
else
echo "nothing detected";
}
}
?>
As you can tell, I tried doing something with comparing the last and the newest ID value but failed miserably.
My attempt would be to store an initial value for oldID and then comparing this to newID before replacing it.
You can't do that only with PHP. But you could do it like this:
If you have a website, you set the current highest ID in the output of php. You can use javascript to call another php script every 5 minutes (or any other time span you find meaningful) that gives you back the current highest number. If the number from the php script is higher, than the number you have in javascript, you can let javascript play a sound for you.
Assuming your php script returns an id like this:
{"id":4}
an example for the javascript call would be this:
<html>
<head></head>
<script>
let highestId = 2;
window.setInterval(async function(){
const response = await fetch('http://localhost/jstest/index.php');
const myJson = await response.json();
console.log(console.log(myJson.id));
if (highestId < myJson.id) {
highestId = myJson.id
// here you can play your sound
$s = document.getElementById('myId');
$s.innerHTML = highestId;
}
}, 5000);
</script>
<body>
<span id="myId">0</span>
</body>
</html>
You can use a cookie variabale to do this. Set the cookie value using php and send the cookie value with php file call. This way you can identify a new highest id.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
var id = getCookie("highest_id");
$('#show').load('data.php?id='+id)
}, 3000);
});
</script>
Add set cookie in the code if the value is changed.
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
$numId = 0;
if ($row = $result->fetch_assoc()) {
$numId = $row['id'];
}
$value = $_GET['id'] ?? 0;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
setcookie("highest_id", $numId, time() - 3600);
} else {
echo "nothing detected";
}
}
?>
Note the points :
In PHP : setcookie("highest_id", $numId, time() - 3600);
In Script : getCookie("highest_id");
My goal is to perform an AJAX request when clicking on a button to retrieve "name" and "story" stored in my database. Each button will get info of another hero.
I'm working on multiple files.
With my current code (which is the closer to what seems to be correct in my mind) the switchHeroInfo will always change the text to "TestName" and "StoryName" instead of "Gertrude" "An old lady"(stored in database).
Can you enlight me on what may be the cause of my struggles?
the php file for connecting to database : connect_database.php
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=biomass;charset=utf8', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Error : '.$e->getMessage());
}
?>
The Javascript part :
$(document).ready(function()
{
$(".hero_portrait").click(function()
{
var index = $(this).data("id");
$.ajax(
{
type: "POST",
url: "../php/get_data.php",
data: {newIndex:index},
success: function(data)
{
// Display {"nick":"Gertrude","0":"Gertrude","story":"Vieille folle senile","1":"Vieille folle senile"}
alert(data);
//Display : undefined
alert(data.story);
$("#hero_name").html(data.nick);
$("#hero_story").html(data.story);
},
error: function()
{
alert("Request failure");
}
});
});
});
The php file : get_data.php
<?php
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
while($data = $sql->fetch())
{
?>
<script>
$heroNameTemp = <?php echo json_encode($data["name"]); ?>;
$heroStoryTemp = <?php echo json_encode($data["story"]); ?>;
</script>
<?php
}
$sql->closeCursor();
?>
Finally the HTML relative to the current problem:
<div id="squad_portraits">
<div class="hero_portrait" id="1"></div>
<div class="hero_portrait" id="2"></div>
<div class="hero_portrait" id="3"></div>
<div class="hero_portrait" id="4"></div>
</div>
<div id="hero_info">
<h2 id="hero_name">Hero_Name</h2>
<p id="hero_story"> Hero_Description</p>
</div>
If i switch my sql request :
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
to this
$tempValue = 4;
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = 4');
AND add the following to my HTML file
<?php include("../php/get_data.php"); ?>
everything works but my index will always be "4".
There are several issues and missunderstandings in your code.
first, in ajax change data to this:
data: {newIndex:index}, // remove the (), simple syntax misstake
This should solve the sql problem.
Now the get_data.php:
<?php
// including db connection is missing here for $bdd
// You should add a test here, wether you've received any and correct data in 'newIndex'
if(empty($_POST['newIndex']) {
// throw an error, send that back to ajax (with a fitting http response code) and exit script
http_response_code(400);
$error = new stdClass();
$error->msg = "Parameter newIndex was missing";
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($error);
exit;
}
$tempValue = $_POST['newIndex'];
// only select the values you need (name, story)
$sql = $bdd->prepare('SELECT name, story FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
$data = $sql->fetch(); // if you only expect/need one row, no while is needed
// echo ONE json string as plain string:
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($data);
Now you receive content of $data as a json as param (data) in the success-callback of your ajax, which you can use like this:
success: function(data){
$("#hero_name").html(data.name);
$("#hero_story").html(data.story);
}
Finally let's change storing the item's id from the id attribute to the data-attribute:
In html:
<div class="hero_portrait" data-id="1"></div>
<div class="hero_portrait" data-id="2"></div>
and in javascript change
var index = $(this).attr("id");
to
var index = $(this).data("id"); // $(this).attr("data-id"); will also work
First of all sorry for the English:)
so hello im a new web programmer and im working on some school manager project.
i have to display all courses in school and then when i click course display his description.
this is my display php code
<?php
$conn = mysqli_connect("localhost", "root", "", "school");
if($conn){
$result = $conn->query("SELECT * FROM `courses`");
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$id=$row['id'];
echo '<div class="alex" onclick="myFunction(this.id)" id="'.$id.'">'.$row['name'].'</div>'.'<br>'.'<br>';
}
}
}else{
echo die("connection faild");
}
mysqli_close($conn);
?>
as you can see i gave it the id of the table which i what to display description.
that is my function code in js file
function myFunction(id){
$.post(
"api/courses/description.php",
{ id:id }
).done(function( data ) {
console.log(id);
$('#desc').load("api/courses/description.php");
});
}
and here is my description php to get id and display description:
<?php $conn = mysqli_connect("localhost", "root", "", "school");
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
if($conn){ $result = $conn->query("SELECT * FROM courses WHERE id = '$id'");
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $row['description'];
}
}
}else{
echo die("connection faild");
}
mysqli_close($conn); ?>
when i click the displayed courses i get the ids on console!
For every course I click I get his id on console.
hope you could help me!
Im sittin on it for many hours and cant get the problem.
hope its readable T_T
edit:forgot to say..
error i have is
Notice: Undefined index: id in
C:\xampp\htdocs\project\api\courses\description.php on line 9---cant
get id NULL ----------------------------------------> on var dump
Notice: Undefined variable: id in
C:\xampp\htdocs\project\api\courses\description.php on line 10
(---->id = $id undefined -> $id)
You're calling description.php twice. First you call it in an AJAX POST request and successfully supply it the id parameter. This does not generate an error. But then look at what you do with the result of that operation:
console.log(id);
$('#desc').load("api/courses/description.php");
You log the id, which is also successful. Then you ignore the data response and call description.php again. This time as an AJAX GET request where you do not supply it with the id parameter. This is what generates the errors.
Instead of making the second request, just use the returned value of the first request. It looks like you want something like this:
console.log(id);
$('#desc').html(data);
I am making a program for a quiz show in our school programme. I have a table that contains WHO asked the question (among the teachers), WHAT is the question and another table as to what the answer to that question is. So, I have a table with THREE COLUMNS.
Now, what I was trying to do is that when the page loads, it will display a number of links labeled . I echoed each link such that when you click any of them, a random row will be taken from MySQL table and the "Question" as well as who asked that particular question will be displayed publicly.
so far, i was able to do all that just fine. But here's the problem.
I want to do it in such a way that after clicking the question, (after displaying it, to be exact,) that specific row will be DELETED from the MySQL table. I didn't want to use a timer because the time allotted for each question differs. I was wondering if there is some kind of "after click" function (or some way to do it) in javascript and AJAX. or perhaps a PHP code?
sorry for the noobish question. History teacher here. :)
by the way, here is a part of my code:
<?php
$checkrow = $db->query("SELECT * FROM questions WHERE `who` = $teachers");
while ($row = $checkrow->fetch(PDO::FETCH_ASSOC))
{
$who = $row['who'];
$question = $row['question'];
$date =$row['date_asked'];
$ask = $db->query("SELECT COUNT(*) FROM teachers WHERE science = $from AND who = $teachers");
$count = $ask->fetch(PDO::FETCH_NUM);
if($count[0] == 0) {
echo ' MYSTERY QUESTION ';
$fromwho = "From science Department.";
echo "<br>";
} else {
echo ' MYSTERY QUESTION ';
$fromwho = "From your Arts Department.";
echo "<br>";
}
}
?>
and here is my javascript.
<script language="javascript">
function readmsg(){
var qst = "<?php echo $question; ?>";
var dte = "<?php echo $date; ?>";
var frm = "<?php echo $fromwho; ?>";
document.getElementById("displaymsg1").textContent = qst;
document.getElementById("displaymsg2").textContent = dte;
document.getElementById("displaymsg3").textContent = frm;
}
</script>
1st, you have to make page delete_question.php (or method like this):
<?php
$db->query(('DELETE FROM questions WHERE ID=' . $_GET['uid']); // make it safer
echo '{result:"done"}';
?>
2nd, make delete onclick handler function with ajax sends UID to specified
function delete_question(el) {
$.ajax({
url : 'delete_question.php',
dataType : 'json',
data : {
uid : el.dataset.uid
},
success : function(response) {
// remove line?
$(el).parent().remove();
alert(response.result);
}
});
3nd: add handler to element
<a href="#" onclick="delete_question(this)" data-uid="<?php echo $row['ID'] ?>">
I have this ajax_update script that updates file.php every 60 seconds..
Now file.php outputs this after updated a table:
<div id='message' style="display: none;">
<span>Hey, <b><? echo $userid; ?></b>, You've got +1 points, you now have <u>
<? echo $n["points"]; ?></u></span>
X
</div>
<script>
$("#message").fadeIn("slow");
</script>
Why will this only work in FF, i mean appear, but not in IE..
What I am trying to do is that after file.php have updated a field in the database(points), there will come up a message like stackoverflow at the top(just like when you earn a badge) saying that you have received 1 point.
This works perfectly in FF but in IE, the message is not showing at all?
Maybe another way to do this? Or a fix, solution?
I tried to put the little JS script in the index.php and remove the ajax update thing, and it works fine in IE.
function addpoints() {
var userid = document.getElementById('user_id_points');
var postFile = 'addpoints.php?userid='+ userid.value;
$.post(postFile, function(data){
$("#message").fadeIn("slow");
$("#points").html(data);
setTimeout(addpoints, 62000);
});
}
function closeNotice() {
$("#message").fadeOut("slow");
}
my ajax script^
<?php
include "tilslut.php";
$userid = $_GET["userid"];
$s = mysql_query("SELECT points, lastpoint FROM member_profile WHERE user_id = '".$userid."'");
$n = mysql_fetch_array($s);
$tid = time();
mysql_query("UPDATE member_profile set points = points+1, lastpoint=$tid WHERE lastpoint<=$tid-60 AND user_id = '".$userid."'");
if(isset($userid)) {
$e = mysql_query("SELECT points FROM member_profile WHERE user_id = '".$userid."'");
$f = mysql_fetch_array($e);
echo $n["points"];
}elseif (mysql_affected_rows() == 1) {
$s = mysql_query("SELECT points FROM member_profile WHERE user_id = '".$userid."'");
$n = mysql_fetch_array($s);
?>
If you receive this text, no problem with php
<div id="message" onclick="closeNotice()">this works
</div>
<?
}else{
?>
This doesnt work at all
<?
}
?>
my php coding, with the
In your ajax update script, call this after the results are in:
$("#message").fadeIn("slow");
Scripts coming back as part of the request are unreliable, putting the logic in your ajax result function is a better approach in this case.
Try this for your ajax call:
function addpoints() {
var postFile = 'addpoints.php?userid='+ $('#user_id_points').val();
$.post(postFile, function(data){
$("#points").html(data).find("#message").fadeIn("slow")
setTimeout(addpoints, 62000);
});
}
Solved this by adding a
header('Content-type: text/html; charset=utf-8');
in the top in addpoints.php