I realized a code for a rate system with five hearts. I would like, when I chose the value of my vote, that the system actualize the average because I must update the page for it.. It must be automatic with my code ... where did I wrong?
my note.js
$(function(){
$('.star').on('mouseover', function(){
var indice = $('.star').index(this);
$('.star').removeClass('full');
for(var i = 0; i<= indice; i++){
$('.star:eq('+i+')').addClass('full');
}
});
$('.star').on('mouseout', function(){
$('.star').removeClass('full');
});
var average = $('.average').attr('data-average');
function avaliacao(average){
average = (Number(average)*20);
$('.barra .bg').css('width', 0);
$('.barra .bg').animate({width: average+'%'}, 500);
}
avaliacao(average);
$('.star').on('click', function(){
var artigoId = $('.artigoDados').attr('data-id');
var ponto = $(this).attr('id');
location.reload();
$.post('sys/votar.php',{votar: 'sim', artigo: artigoId, ponto: ponto}, function(retorno){
avaliacao(retorno.average);
$('p.votos span').html(retorno.votos);
}, 'jSON');
});
});
My html code:
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
?>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/note.js"></script>
</head>
<body>
<?php
$artigoId = (int)$_GET['artigo'];
$artigos = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$artigos->execute(array($artigoId));
while($row = $artigos->fetchObject()){
echo '<h1>'.$row->titre_recette.'</h1>';
$calculo = ($row->pontos == 0) ? 0 : round(($row->pontos/$row->votos), 1);
echo '<span class="average" data-average="'.$calculo.'"></span>';
echo '<span class="artigoDados" data-id="'.$row->id_recette.'"></span>';
?>
<div class="barra">
<span class="bg"></span>
<div class="estrelas">
<?php for($i=1; $i<=5; $i++): ?>
<span class ="star" id="<?php echo $i;?>">
<span class="starAbsolute"></span>
</span>
<?php endfor;?>
</div>
</div>
<p class="votos"><span><?php echo $row->votos;?></span>votes</p>
<?php }?>
</body>
</html>
votar.php
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$artigo = (int)$_POST['artigo'];
$pontos = $_POST['ponto'];
$pegaArtigo = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$pegaArtigo->execute(array($artigo));
while($row = $pegaArtigo->fetchObject()){
$votosUpd = $row->votos+1;
$pontosUpd = $row->pontos+$pontos;
$average = round(($pontosUpd/$votosUpd), 1);
$update = $bdd->prepare('UPDATE sys_note SET votos = ?, pontos = ? WHERE id_recette = ?');
if($update->execute(array($votosUpd, $pontosUpd, $artigo))){
die(json_encode(array('average' => $average, 'votos' => $votosUpd)));
}
}
}
?>
Related
I am creating screen share with SEE server, everything is working properly
when the user opens a room for screen share he enters a room
But when the second user wants to turn it on room nothing happens
I checked and error gives no room found
How I can resolve that?
(i test script with socket.io server it's working properly)
my front end code :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>SSE+PHP Signaling using RTCMultiConnection</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<link rel="shortcut icon" href="logo.png">
<link rel="stylesheet" href="stylesheet.css">
<script src="menu.js"></script>
</head>
<body>
<header>
<a class="logo" href="/"><img src="logo.png" alt="RTCMultiConnection"></a>
Menu<img src="menu-icon.png" alt="Menu">
<nav>
<li>
Home
</li>
<li>
Demos
</li>
<li>
Getting Started
</li>
<li>
FAQ
</li>
<li>
YouTube
</li>
<li>
Wiki
</li>
<li>
Github
</li>
</nav>
</header>
<h1>
SSE+PHP Signaling using RTCMultiConnection
<p class="no-mobile">This demo is using SSE (Server Sent Events) to setup WebRTC one-to-one connection. Check PHP Source Codes</p>
</h1>
<section class="make-center">
<input type="text" id="room-id" value="abcdef" autocorrect=off autocapitalize=off size=20>
<button id="open-room">Open Room</button>
<button id="join-room">Join Room</button>
<button id="open-or-join-room">Open or Join Room</button>
<div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div>
<div id="videos-container"></div>
</section>
<script src="adapter.js"></script>
<script src="RTCMultiConnection.js"></script>
<script src="SSEConnection.js"></script>
<link rel="stylesheet" href="getHTMLMediaElement.css">
<script src="getHTMLMediaElement.js"></script>
<script>
window.enableAdapter = true; // enable adapter.js
// ......................................................
// .......................UI Code........................
// ......................................................
document.getElementById('open-room').onclick = function() {
disableInputButtons();
connection.open(document.getElementById('room-id').value, function() {
showRoomURL(connection.sessionid);
});
};
document.getElementById('join-room').onclick = function() {
disableInputButtons();
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: false,
OfferToReceiveVideo: true
};
console.log(document.getElementById('room-id').value);
connection.join(document.getElementById('room-id').value);
};
document.getElementById('open-or-join-room').onclick = function() {
disableInputButtons();
// connection.openOrJoin(document.getElementById('room-id').value);
connection.checkPresence(document.getElementById('room-id').value, function(isRoomExist, roomid) {
console.info('checkPresence', isRoomExist, roomid);
if(isRoomExist) {
connection.join(roomid);
}
else {
connection.open(roomid);
}
});
};
// ......................................................
// ..................RTCMultiConnection Code.............
// ......................................................
var connection = new RTCMultiConnection();
// Using SSE (Server Sent Events) for signaling
connection.socketURL = 'https://127.0.0.1/see/';
connection.setCustomSocketHandler(SSEConnection);
connection.session = {
screen: true,
oneway: true
};
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
// https://www.rtcmulticonnection.org/docs/iceServers/
// use your own TURN-server here!
connection.iceServers = [{
'urls': [
'stun:stun.l.google.com:19302',
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
'stun:stun.l.google.com:19302?transport=udp',
]
}];
connection.videosContainer = document.getElementById('videos-container');
connection.onstream = function(event) {
event.mediaElement.id = event.streamid;
connection.videosContainer.appendChild(event.mediaElement);
if (event.type === 'remote') {
connection.socket.close(); // release SSE connection
}
};
connection.onstreamended = function(event) {
var mediaElement = document.getElementById(event.streamid);
if (mediaElement && mediaElement.parentNode) {
mediaElement.parentNode.removeChild(mediaElement);
}
};
function disableInputButtons() {
document.getElementById('open-room').disabled = true;
document.getElementById('join-room').disabled = true;
document.getElementById('open-or-join-room').disabled = true;
document.getElementById('room-id').disabled = true;
}
// ......................................................
// ......................Handling Room-ID................
// ......................................................
function showRoomURL(roomid) {
var roomHashURL = '#' + roomid;
var roomQueryStringURL = '?roomid=' + roomid;
var html = '<h2>Unique URL for your room:</h2><br>';
html += 'Hash URL: ' + roomHashURL + '';
html += '<br>';
html += 'QueryString URL: ' + roomQueryStringURL + '';
var roomURLsDiv = document.getElementById('room-urls');
roomURLsDiv.innerHTML = html;
roomURLsDiv.style.display = 'block';
}
(function() {
var params = {},
r = /([^&=]+)=?([^&]*)/g;
function d(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
}
var match, search = window.location.search;
while (match = r.exec(search.substring(1)))
params[d(match[1])] = d(match[2]);
window.params = params;
})();
var roomid = '';
if (localStorage.getItem(connection.socketMessageEvent)) {
roomid = localStorage.getItem(connection.socketMessageEvent);
} else {
roomid = connection.token();
}
document.getElementById('room-id').value = roomid;
document.getElementById('room-id').onkeyup = function() {
localStorage.setItem(connection.socketMessageEvent, this.value);
};
var hashString = location.hash.replace('#', '');
if (hashString.length && hashString.indexOf('comment-') == 0) {
hashString = '';
}
var roomid = params.roomid;
if (!roomid && hashString.length) {
roomid = hashString;
}
if (roomid && roomid.length) {
document.getElementById('room-id').value = roomid;
localStorage.setItem(connection.socketMessageEvent, roomid);
// auto-join-room
connection.join(roomid);
disableInputButtons();
}
</script>
<footer>
<small id="send-message"></small>
</footer>
</body>
</html>
PHP side :
https://github.com/muaz-khan/RTCMultiConnection/tree/master/demos/SSEConnection
I'm a complete beginner and have built a basic To-Do List application using PHP/jQuery. The application allows the user to add and remove tasks from a list (stored in a MySQL database).
I'm having issues with the delete function. When the delete button is clicked, it removes the task from the list but it must be remaining in the database, as it reappears once the page is refreshed.
I have no idea where I'm going wrong! Any help appreciated. See below code:
index.php :
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" type="text/css" href="/style.css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="list">
<ul>
<?php
require("db_connect.php");
$query = mysql_query("SELECT * FROM tasks ORDER BY date ASC, time ASC");
$numrows = mysql_num_rows($query);
if($numrows>0) {
while ( $row = mysql_fetch_assoc( $query ) ){
$task_id = $row['task_id'];
$task_desc = $row['task_desc'];
echo '<li><span>'.$task_desc.'</span><img id="'.$task_id.'" class="delete" width="10px" src="images/delete.png" /></li>';
}
}
?>
</ul>
</div>
<form class="new" autocomplete="off">
<input type="text" name="new-task" placeholder="Add a new task..." />
</form>
</div>
</body>
<script>
add_task();
delete_task();
function add_task() {
$('.new').submit(function() {
var new_task = $('.new input[name=new-task]').val();
if(new_task !== '') {
$.post('add_task.php', { task: new_task }, function ( data ) {
$('.new input[name=new-task]').val('');
$(data).appendTo('.list ul').hide().fadeIn();
delete_task();
});
}
return false;
});
}
function delete_task() {
$('.delete').click(function() {
var current_element = $(this);
var task_id = $(this).attr('task_id');
$.post('delete_task.php', { task_id: task_id }, function() {
current_element.parent().hide().fadeOut("fast", function() {
$(this).remove();
});
});
});
}
</script>
delete_task.php :
<?php
$task_id = strip_tags( $_POST['task_id'] );
require("db_connect.php");
mysql_query("DELETE FROM tasks WHERE task_id='$task_id'");
?>
You have an error in your delete_task function. There is no such attr as 'task_id'. Try to replace
var task_id = $(this).attr('task_id');
With
var task_id = $(this).attr('id');
Besides #IvanGajic answer is correct, also write your delete query like this:
mysql_query('DELETE FROM tasks WHERE task_id="' . $task_id . '"');
I realized a code for a rate system but when I select a vote, nothing change, when I reselect again a vote, it's ok ! BUT when I see my DB on phpmyadmin, the counter of vote has 1 clic in more than the counter of vote that I "echoed" on my page... why this difference of 1?
my note.js
$(function(){
$('.star').on('mouseover', function(){
var indice = $('.star').index(this);
$('.star').removeClass('full');
for(var i = 0; i<= indice; i++){
$('.star:eq('+i+')').addClass('full');
}
});
$('.star').on('mouseout', function(){
$('.star').removeClass('full');
});
var average = $('.average').attr('data-average');
function avaliacao(average){
average = (Number(average)*20);
$('.barra .bg').css('width', 0);
$('.barra .bg').animate({width: average+'%'}, 500);
}
avaliacao(average);
$('.star').on('click', function(){
var artigoId = $('.artigoDados').attr('data-id');
var ponto = $(this).attr('id');
location.reload();
$.post('sys/votar.php',{votar: 'sim', artigo: artigoId, ponto: ponto}, function(retorno){
avaliacao(retorno.average);
$('p.votos span').html(retorno.votos);
}, 'jSON');
});
});
My html code:
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
?>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/note.js"></script>
</head>
<body>
<?php
$artigoId = (int)$_GET['artigo'];
$artigos = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$artigos->execute(array($artigoId));
while($row = $artigos->fetchObject()){
echo '<h1>'.$row->titre_recette.'</h1>';
$calculo = ($row->pontos == 0) ? 0 : round(($row->pontos/$row->votos), 1);
echo '<span class="average" data-average="'.$calculo.'"></span>';
echo '<span class="artigoDados" data-id="'.$row->id_recette.'"></span>';
?>
<div class="barra">
<span class="bg"></span>
<div class="estrelas">
<?php for($i=1; $i<=5; $i++): ?>
<span class ="star" id="<?php echo $i;?>">
<span class="starAbsolute"></span>
</span>
<?php endfor;?>
</div>
</div>
<p class="votos"><span><?php echo $row->votos;?></span>votes</p>
<?php }?>
</body>
</html>
votar.php
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$artigo = (int)$_POST['artigo'];
$pontos = $_POST['ponto'];
$pegaArtigo = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$pegaArtigo->execute(array($artigo));
while($row = $pegaArtigo->fetchObject()){
$votosUpd = $row->votos+1;
$pontosUpd = $row->pontos+$pontos;
$average = round(($pontosUpd/$votosUpd), 1);
$update = $bdd->prepare('UPDATE sys_note SET votos = ?, pontos = ? WHERE id_recette = ?');
if($update->execute(array($votosUpd, $pontosUpd, $artigo))){
die(json_encode(array('average' => $average, 'votos' => $votosUpd)));
}
}
}
?>
You need to do location.reload(); after you the post, not before.
$.post('sys/votar.php',{votar: 'sim', artigo: artigoId, ponto: ponto}, function(retorno){
location.reload();
}, 'jSON');
There is no point to do the extra work inside the callback since you are reloading the page anyway.
Although, I would recommend you change the elements on the page via ajax instead of the crude location.reload();
I'm trying to build a comment system
this is my code
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<style>
.back_glob{width: 350px}
</style>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(function(){
$( ".tombol_login" ).click(function() {
var txt = $("[name=comment]").val();
$("#comment").submit();
})});
</script>
<style>
.back_glob{width: 450px}
</style>
</head>
<body>
<div class = "back_glob">
<div class="tableC">
<img src="img\back.png" alt="back" height="42" width="42">
<div class ="back_header">
<h4>comment</h4>
</div>
<div class= "table">
<form id="comment" name="comment" action="contet2.php" method="post">
<div class="row">
<div class="col">comment</div>
<div class="col">:</div>
<div class="col"><textarea name="comment" rows ="10" cols="40"></textarea></div>
</div>
<div class="tom">
<button type="button" class="tombol_login">Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
$servername = "localhost";
$dbname = "databaseform";
$username = "root";
$password = "";
session_start();
$page = 2;
$conn = new PDO("mysql:host =$servername ; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT form.Username, comment.Comment, comment.time FROM
form, comment WHERE
form.pkey=comment.pkey AND
comment.page=$page
ORDER BY comment.time DESC";
$result = $conn->query($query);
$hasil = $result->fetchAll();
$Comment = $_POST['comment'];
try
{
// injec
$query = "INSERT INTO comment (pkey,Comment,time,page)
VALUES (:Username,:Comment,NOW(),:page)";
$sql = $conn->prepare($query) ;
$sql->BindValue(':Username',reset($_SESSION['txt_login']));
$sql->BindValue(':Comment',$Comment);
$sql->BindValue(':page',$page);
$sql->execute();
$query = "SELECT form.Username, comment.Comment, comment.time FROM
form, comment WHERE
form.pkey=comment.pkey AND
comment.page=$page
ORDER BY comment.time DESC";
$result = $conn->query($query);
$hasil = $result->fetchAll();
echo '<div class="back_glob">';
echo '<div class = "table">';
echo '<div class = "tableC">';
echo '</div>';
}
catch(PDOException $e)
{
echo $query . "<br>" . $e->getMessage();
}
for($i = 0 ; $i < count($hasil);$i++)
{
echo'<div class="row">';
echo '<div class="col2">'.$result[$i]['Username'].'</div>';
echo '<div class="col2">'.$result[$i]['Comment'].'</div>';
echo '<div class="col2">'.$result[$i]['time'].'</div>';
echo'</div>';
}
?>
but the php part won't recognize the $_POST['comment'] before the submit button , i can't show the previous comment unless I click the submit button.
Is there any solution to correct this ??
I am really confused about your way of asking a question. I think you should have to read this tutorial of Smashing Magazine. So you can better understand of code and comment system.
I hope it will help you.
Hello stackoverflow,
I am trying to make a search function to search events on a Search API.
The API can be viewed here: http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=opera this is the output XML if you search on the word "opera".
I'm still quite a noob at PHP so i"m having a hard time. I used this tutorial/example as help:http://designm.ag/tutorials/deviantart-api-instant-search-app-using-ajax-php/
So I built my code and I ended up getting the error "Error: parsererror" every time I type in a keyword in the text area. Can anyone help me fix this please?
Here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Culture Reminder</title>
<!-- Stylesheets -->
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
<!-- Scripts -->
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<!-- <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> -->
<script type="text/javascript" src="uitdatabase.js"></script>
<!-- HTML5 Shiv -->
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<h1>Search events</h1>
</header><!-- /header -->
<div id="container">
<div id="searchform">
<h2>Search for culture</h2>
<input id="s" name="s" placeholder="Type in keyword(s)" size="30" type="text" />
</div><!-- /searchform -->
<center id="loader"><img src="images/loader.gif" alt="loading..."></center>
<div id="content">
</div><!-- /content -->
</div><!-- /container -->
<div id="footer">
<div id="nav">
<img src="images/searchbutton.gif" />
<img src="images/mylistbutton.gif" />
<img src="images/settingsbutton.gif" />
</div>
</div><!-- /footer -->
</body>
</html>
Here is the Javascript file:
$(document).ready(function(){
var s = $("#s");
var wrap = $("#content");
var delay = 1500;
var keycode;
var timer;
$(s).keydown(function(e){
// clear old page content and reset timer
$(wrap).empty();
clearTimeout(timer);
});
$(s).keyup(function(){
$("#loader").css("display", "block");
timer = setTimeout(startSearch, delay); // end timeout() function
}); // end keyup() event function
function startSearch() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: "q="+$(s).val(),
success: function(data){
// hide the loader and blur focus away from input
$("#loader").css("display", "none");
$(s).blur();
var code = "<span class=\"results\">Total Results: "+data['total']+"</span>";
$.each(data, function(i, item) {
if(typeof(data[i].title) !== 'undefined') { // check if data is undefined before setting more variables
code = code + '<div class="listing clearfix"><header><h3>'+data[i].title+'</h3><span class="userdata"><span class="date">'+data[i].calendarsummary+'</span>'+'<span class="location">' + data[i].location+'</span>'+'<span class="description">'+ data[i].shortdescription+'</span></span></header></div>';
code = code + '<img src="'+data[i].thumbnail+'" class="thumbnail">';
}
});
$(wrap).html(code);
},
error: function(xhr, type, exception) {
$("#loader").css("display", "none");
$(wrap).html("Error: " + type);
}
}); // end ajax call
}
}); // end ready() function
And here is my ajax.php code:
<?php
header('Content-Type: application/json');
$query = urlencode(stripslashes($_POST['q']));
$keywords = $query;
$xmlurl = "http://http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=".$keywords;
$xmlrss = file_get_contents($xmlurl);
$xmlrss = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlrss);
$object = simplexml_load_string($xmlrss);
// setup return array
$return = array();
$i = 0;
// get total number of results, max 60
$total = count($object->list->item);
$return["total"] = $total;
foreach($object->list->item as $item) {
$title = (string) $item->title;
$date = (string) $item->calendarsummary; //url
$loc = (string) $item->location; // authorname
$desc = (string) $item->shortdescription;//authorpic
$thumburl = (string) $item->thumbnail;//authorpic
// configure array data for each item
$return[$i]["title"] = $title;
$return[$i]["calendarsummary"] = $date;
$return[$i]["location"] = $loc;
$return[$i]["shortdescription"] = $desc;
$return[$i]["thumbnail"] = $thumburl;
$i++;
}
$json = json_encode($return);
die($json);
?>
If anyone could help me I would be so grateful. This is a project for school and I'm still learning basic PHP.
Try this code
<?php
header('Content-Type: application/json');
if(isset($_POST['q']))
{
$query = urlencode(stripslashes($_POST['q']));
$keywords = $query;
$xmlurl = "http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=".$keywords;
$xmlrss = file_get_contents($xmlurl);
$xmlrss = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlrss);
$object = simplexml_load_string($xmlrss);
// setup return array
$return = array();
$i = 0;
if(isset($object->list->item))
{
// get total number of results, max 60
$total = count($object->list->item);
$return["total"] = $total;
if($total>0)
{
foreach($object->list->item as $item) {
$title = (string) $item->title;
$date = (string) $item->calendarsummary; //url
$loc = (string) $item->location; // authorname
$desc = (string) $item->shortdescription;//authorpic
$thumburl = (string) $item->thumbnail;//authorpic
// configure array data for each item
$return[$i]["title"] = $title;
$return[$i]["calendarsummary"] = $date;
$return[$i]["location"] = $loc;
$return[$i]["shortdescription"] = $desc;
$return[$i]["thumbnail"] = $thumburl;
$i++;
}
$json = json_encode($return);
die($json);
}else{
//count is empty
}
}else{
//object is not ready
}
}else{
//no post data found
}