I have a question:
I'm trying to create a Personal-Message-System on my Website and for this one my Idea was, that the user gets displayed the amount of new messages in each chat...
As in this screenshot
Yes, I am from germany, so the language in the screenshot is german...
You see the red "box" with the number in it? This one I want to create for each chat and I don't know how. With PHP only this would be easy, but I want, that the numbers are right always and refreshes automaticly...
So my HTML-Code is:
<div class="chat_body">
<a href="index.php?section=pn&mode=loadConversation&ConversationID=<?php echo $conversation['id']; ?>">
<div class="user" id='<?php echo $i ?>' data-user-id='<?php echo $user_id?>' data-conv-id='<?php echo $conversation['id'] ?>'>
// Displaying the name, etc... (for clarity i left it out)
<?php
echo "<div class='rightCountUnreadMessages'>";
echo '<div class="badge" id="badge-'.$i.'"></div>';
echo "</div>";
?>
</div>
</a>
</div>
At the top of the page my Javascript, to load the numbers, is:
jQuery(document).ready(function() {
//jQuery(setInterval(function() {
friends_count = document.getElementsByClassName("user").length;
for(var i=1; i < friends_count+1; i++) {
el = document.getElementById(i);
conv_id = el.getAttribute("data-conv-id");
user_id = el.getAttribute("data-user-id");
test = i;
jQuery.post('./Bauteile/Accounts/loadCounts/loadPNCount.php', {user_id_loadPN: user_id, conv_id: conv_id}, function(result){
console.log(result);
console.log(test);
if(result > 99) {
result = "99+";
}
if(result > 0 || result == "99+") {
document.getElementById("badge-"+test).innerHTML = result;
}
})
}
//}, 500));
});
And in the requested document in Javascript has the following content:
<?php
$conv_id = $_POST['conv_id'];
$from_id = $_POST['user_id_loadPN'];
echo (int)mysql_result(mysql_query("SELECT COUNT(*) FROM `messages` WHERE `group_id` = $chat_id AND `from_id` = $from_id AND `read_on` is NULL"), 0);
?>
I know it is difficult to see through all of this, but I hope someone can help me...
I don't know what I do wrong, but the code doesn't work...
I think it is probably because of the for loop but I don't know, how I fix this...
If you have questions please ask...
Thank you in advance
The problem is you have something asynchronous in your loop. To solve this problem you need a closure. You need to wrap the content of the for loop in a function that takes i as a parameter, then call the function in the loop.So try something like this :
function doClosure(i) {
var el = document.getElementById(i),
conv_id = el.getAttribute("data-conv-id"),
user_id = el.getAttribute("data-user-id"),
test = i;
jQuery.post('./Bauteile/Accounts/loadCounts/loadPNCount.php', {user_id_loadPN: user_id, conv_id: conv_id}, function(result){
console.log(result);
console.log(test);
if(result > 99) {
result = "99+";
}
if(result > 0 || result == "99+") {
document.getElementById("badge-"+test).innerHTML = result;
}
});
}
for (var i = 1; i < document.getElementsByClassName("user").length+1; i++) {
doClosure(i);
}
Addition to my post:
I replaced
jQuery.post('./Bauteile/Accounts/loadCounts/loadPNCount.php', {user_id_loadPN: user_id, conv_id: conv_id}, function(result){
with
console.log(user_id + " " + i);
jQuery.post('./Bauteile/Accounts/loadCounts/loadPNCount.php', {user_id_loadPN: user_id, conv_id: conv_id}, function(result){
console.log(result + " " + i);
for debugging...
The console output was:
21 1 line: 254 (= first console.log in this example)
26 2 line: 254
27 3 line: 254
26 4 line: 256 (= sec. console.log in this example)
27 4 line: 256
21 4 line: 256
So, as i suspected the For-loop and the jQuery function doesn't work together very well...
Related
My site pulls test questions from a database, and some of these questions have images associated with them.
The images pull in fine and everything works as expected, but when trying to pull the answers for these questions, which sometimes also have images, there is a translation issue causing just the reference index to be called and no image displayed (the text still appears that is associated with the answer however).
Question Picture Example
Answer Picture Example - An image should appear in the highlighted area
I can't tell if the issue is caused in the HTML/PHP interpretation of calling an answer or in the function that defines the answer to be called. Code snippets below.
First is the HTML/PHP and JS. All things pertaining to answers are "Rationale" All things pertaining to images are "equations":
<?php
for ($i = 0; $i < $displayCount; $i++) {
$workingDate = date('Y-m-d', time()-($i*24*60*60));
$QID = updateQOTD($ar, $workingDate, $level);
$questionInfo = getQuestion($ar, $QID);
echo $workingDate."<br><br>";
if(isset($questionInfo->VIGNETTE)) {
echo "<strong>Vignette</strong>:<br>";
echo $questionInfo->VIGNETTE;
echo "<br><br>";
}
$equation = getEquation($ar, $QID);
$eq_text = '';
if (isset($equation)) {
$file = $equation->FILE_NAME;
$eq_text = '<img src="/lcms/images/equations/' . $file . '">';
}
echo "<strong>Question</strong>:<br><br>";
$qtext = $questionInfo->TEXT ;
$qtext = preg_replace('/<equation id="\d+"\/>/', $eq_text, $qtext);
echo $qtext;
echo "<br><br>";
?>
<div id='response_<?php echo $i; ?>'></div>
<div class='rationale margin-top-20'><br><strong>Rationale:</strong><br>
<?php echo $questionInfo->RATIONALE; ?>
</div>
<?php
}
?>
<button id="grade" class="btn-theme" type="button">Grade My Choices</button>
<? require_once(getenv("DOCUMENT_ROOT")."/inc/footer.pilot.php"); ?>
<script type="text/javascript">
$(document).ready(function(){
$(".rationale").hide();
$("response_1").hide();
$("response_2").hide();
$("response_3").hide();
$("response_4").hide();
$("response_5").hide();
$("#grade").click(function () {
$(".correctMark").html("<img src='../../images/600px-Green_check.png' />");
$(".incorrectMark").html("<img src='../../images/600px-Red_x.png' />");
$(".rationale").slideDown("fast");
if ($("input[name='question_1']:checked").val() == 'correct') {
$("#response_1").text("Your answer was correct!");
$("#response_1").slideDown("slow");
}
});
});
</script>
And here is the database code call SQL and function defining Rationale:
function getEquation($ar, $QID) {
if (isset($QID) && $QID > 0) {
$selectSql = sprintf("SELECT e.FILE_NAME FROM equation_tbl e, equation_question_link_tbl eq WHERE eq.QUESTION_ID = %s AND e.ID = eq.EQUATION_ID ",
$QID);
$equation = $ar->get_row($selectSql);
return $equation;
}
}
function getQuestion($ar, $QID) {
$selectSql = sprintf("SELECT case_tbl.TEXT as VIGNETTE, question_tbl.TEXT, question_tbl.ANSWER_1, question_tbl.ANSWER_2, question_tbl.ANSWER_3, question_tbl.ANSWER_4, question_tbl.ANSWER_5, question_tbl.ANSWER_6, question_tbl.ANSWER_7, question_tbl.ANSWER_8, question_tbl.RATIONALE FROM question_tbl LEFT JOIN case_tbl ON question_tbl.CASE_ID = case_tbl.ID WHERE question_tbl.ID = %s",
$QID);
$question = $ar->get_row($selectSql);
return $question;
}
function makeAnswerArray($questionInfo) {
$answers[0] = array($questionInfo->ANSWER_1, 'correct');
$answers[1] = array($questionInfo->ANSWER_2, 'incorrect');
$answers[2] = array($questionInfo->ANSWER_3, 'incorrect');
if(isset($questionInfo->ANSWER_4) && $questionInfo->ANSWER_4 > ' ') {
$answers[3] = array($questionInfo->ANSWER_4, 'incorrect');
if(isset($questionInfo->ANSWER_5) && $questionInfo->ANSWER_5 > ' ') {
$answers[4] = array($questionInfo->ANSWER_5, 'incorrect');
if(isset($questionInfo->ANSWER_6) && $questionInfo->ANSWER_6 > ' ') {
$answers[5] = array($questionInfo->ANSWER_6, 'incorrect');
if(isset($questionInfo->ANSWER_7) && $questionInfo->ANSWER_7 > ' ') {
$answers[6] = array($questionInfo->ANSWER_7, 'incorrect');
if(isset($questionInfo->ANSWER_8) && $questionInfo->ANSWER_8 > ' ') {
$answers[7] = array($questionInfo->ANSWER_8, 'incorrect');
}
}
}
}
}
return $answers;
}
Is there any reason why the images associated with Rationales are not pulling through when expected?
I would start by checking the values of $equation with var_dump($equation) and also var_dump($question) to look for any anomalies. I suspect you've got incomplete data creeping in that looks like /lcms/images/equations/NULL or something similar which should be obvious enough, when dumped.
If this is the case, look at extending your handling of these vars to be more strict about the expected value.
Truth be told, it's going to be difficult to help if we cannot run the code. But I would start by checking data integrity of the MySQL result. Bit of a SQL join in there too that only you will know the correct format of, which would be my next port of call.
I'm new to PHP and I have little knowledge of Javascript, I'm trying to create a chronometer that the time limit is obtained from a database (SQL SERVER), so when you get the value in PHP and assign it to a variable of Javascript function, I get a -1.
From what I read it appears to me that the PHP object type is not the same as in Javascript and this can be solved with json_encode (), however it keeps appearing -1.
<?php
require('db.php');
if ($connection)
{
$TimEva = 60;
$rs = odbc_exec($connection,"SELECT time FROM DBO.tablaCrono cr WHERE cr.id = '$EncIdx';");
while(odbc_fetch_row($rs))
{
$TimEva=odbc_result($rs,"TimEva");
}
echo "<div align='center'><h1><label id = 'tiempo'>".$TimEva."</label></h1></div>";
$rs = odbc_close($connection);
}
else
{
echo "<div align='center'>no se pudo conectar</div><br />";
}
?>
And in the Javascript function I have the following
var label = document.getElementById("tiempo"),
minutos = <?php echo json_encode($TimEva,JSON_HEX_TAG);?>,
I expect 60, which is the value in the database, it shows up well in html, but the value of the variable minutes, throws -1
I could be guided, help, use AJAX, I'm really a bit lost.
$rs = odbc_exec($connection,"SELECT `time` FROM DBO.tablaCrono cr WHERE cr.id = '$EncIdx';");
Change your query to this. time is a word used from the language so if you want to use it as a column you need to escape it.
Also modify your JS code to something like :
<script>
var label = document.getElementById("tiempo")
var minutos = <?php echo json_encode($TimEva,JSON_HEX_TAG);?>
console.log(minutes)
</script>
Then open your console window and see what is the value that your variable has.
Lastly ensure that you actually have a value in $EncIdx variable cause we don't see how you assign a value to it. I guess it's in a part of the code you did not share.
<script>
function tiempo()
{
var label = document.getElementById("tiempo"),
minutos = <?php echo json_encode($TimEva,JSON_NUMERIC_CHECK);?>,
segundos = 0,
intervalo = setInterval(function(){
console.log(minutos)
if (--segundos < 0){
segundos = 59;
minutos--;
}
if (!minutos && !segundos)
{
clearInterval(intervalo);
alert("Lo sentimos se termino el tiempo");
//document.evaluacion.submit();
}
label.innerHTML = minutos + ":" + (segundos < 10 ? "0" + segundos : segundos);
}, 1000);
}
</script>
Right now I have this code:
function addButton() {
var button1 = "<div id=\"number\" class=\"inner\" style=\"display:inline-block; margin-top:5px; margin-right: 5px;\"><p></p></div>" // Create text with HTML
var button2 = button1.replace("number", number)
$("#buttonz").append(button2); // Append new elements
number += 1
};
window.onload = addButtons;
var slots = '<?php echo $slots ?>';
var s = 0;
function addButtons() {
for (i = 0; i < slots; i++) {
addButton();
}
$( document ).ready(function() {
$('#buttonz').on('click', '.inner', function () {
$(this).toggleClass("selected inner");
$('#meem').text(++s);
$('#price').text((s * <?php echo $ticketPrice ?>).toFixed(2));
});
$('#buttonz').on('click', '.selected', function () {
$(this).toggleClass("selected inner");
$('#meem').text(--s);
$('#price').text((s * <?php echo $ticketPrice ?>).toFixed(2));
});
});
}
function buySlots() {
if ((s * <?php echo $ticketPrice; ?>).toFixed(2) > <?php echo $credits; ?>)
{
alert('You do not have enough money...');
}
else
{
alert('You have enough money...');
}
}
This code is part of the code that makes this: http://csgolessons.com/big-raffle.php (You have to login through steam)
I have the selection and price sorted out, but I want people to be able to select X amount of slots, press a button (that makes #ofslots * price be deducted from your account) and then replaces it with a picture I have stored in my database.
I have a database that looks like this (picture url isn't actually insertlink.com):
id | isTaken | pictureURL |
1 0 insertlink.com
2 0 insertlink.com
3 0 insertlink.com
...
145 0 insertlink.com
What I want to know is how do I make the squares have a picture instead of the "inner" class?
How do I make a php file that would upload which buttons had been selected?
Thanks, and if you need clarification just ask.
I have a list of filenames
aeyrt.php
nviorf.php
vyutkd.php
oiuybd.php
poiuuy.php
Suppose that the current opened page is vyutkd.php
I have two arrows < and >
My question is how using PHP or Javascript the < will link to nviorf.php and the > to oiuybd.php ?
The same scenario goes if the current page is the first one. The < button should go to the last of the list.
Thank you
You could put the files name into an array:
$pages= Array( 'aeyrt.php','nviorf.php','vyutkd.php','oiuybd.php','poiuuy.php');
And create a function that check the current file name position and return a link to the previous or next page.
function getLink($pages,$previous = true){
$position = array_search(basename(__FILE__),$pages);
if($position==0 && $previous){
return "<a href='".$pages[count($pages)-1]."'>Previous</a>";
}
if($position==count($pages)-1 && !$previous){
return "<a href='".$pages[0]."'>Next</a>";
}
if($previous && $position!==null && $position>0){
return "<a href='".$pages[$position-1]."'>Previous</a>";
}
if($position!==null && $position<count($pages)-1){
return "<a href='".$pages[$position+1]."'>Next</a>";
}
}
I did not check if it work, but I think so ;)
I modified the funtion to be circular
Would be something like this:
corrected code:
<?php
$pages = array('aeyrt.php','nviorf.php','vyutkd.php','oiuybd.php','poiuuy.php');
$current_file = basename(__FILE__);
if(($current_id = array_search($current_file,$pages))){
if($current_id == count($pages) - 1){
echo "previous";
}else{
echo "previous next";
}
}else{
echo "next";
}
?>
But... I would personally put those links into database and use rewrite rules.
I am having an issue with my javascript. I am trying to count marks for each correct chosen answer which is determined from db. If incorrect answer then marks is '0', else mark is dependent on answer's mark in db.
But I am having issues with the javascript:
First of all where it says connect.php, this just simply navigates to page where it connects to db, but is this correct or am I suppose to link to page where it will run query looking up answer's marks?
Second it says I have undefined response in my code and I do not what this should be called.
My question is can I have clarification for the above 2. I am trying to use ajax and javascript and will appreciate if a strong programmer can tackle this issue I am having and be able to correctly set up the code so that it is able to count each correct answer marks.
I have a jsfiddle which I am trying to follow but if somebody can edit fiddle to have a dummy version working for counting marks and then be able to provide code snippet stating what the proper code should be, then this will help me very much.
At moment the jsfiddle determines if answers selected are correct or incorrect and fiddle is here: http://jsfiddle.net/bWthd/3/
Actual code:
PHP/HTML:
$qandaquery = "SELECT q.QuestionId, Answer, AnswerMarks, OptionType
FROM Question q
INNER JOIN Answer an ON q.QuestionId = an.QuestionId
INNER JOIN Option_Table o ON q.OptionId = o.OptionId
WHERE SessionId = ?
GROUP BY q.QuestionId
ORDER BY RAND()";
...
$qandaqrystmt->bind_result($qandaQuestionId,$qandaAnswer,$qandaAnswerMarks,$OptionType);
$arrQuestionId = array();
while ($qandaqrystmt->fetch()) {
$arrQuestionId[ $qandaQuestionId ] = $qandaQuestionId;
}
foreach ($arrQuestionId as $key=>$question) {
?>
<div class="queWrap" data-q_id="<?php echo $key; ?>">
$options = explode('-', $arrOptionType[$key]);
if(count($options) > 1) {
$start = array_shift($options);
$end = array_shift($options);
do {
$options[] = $start;
}while(++$start <= $end);
}
else{
$options = explode(' or ', $option);
}
if($arrReplyType[$key] == 'Single'){
foreach($options as $indivOption) {
echo '<div class="ck-button"><label class="fixedLabelCheckbox"><input type="radio"
name="options_<?php echo $key; ?>[]" id="option-' . $indivOption . '" value="' .
$indivOption . '" /><span>' . $indivOption . '</span></label></div>';
}
}else if($arrReplyType[$key] == 'Multiple'){
foreach($options as $indivOption) {
echo '<div class="ck-button"><label class="fixedLabelCheckbox"><input type="checkbox" name="options_<?php echo $key; ?>[]" id="option-' . $indivOption . '" value="' . $indivOption . '" /><span>' . $indivOption . '</span></label></div>';
}
}
<p><input type='text' class='questionIds' name='questionids' value='<?php echo htmlspecialchars($arrQuestionId[$key]); ?>' /></p>
}
JAVASCRIPT/AJAX:
$(function() {
$('.queWrap .ck-button').change(function() {
var $ch_box = $(this),
$qwrap=$ch_box.closest('.queWrap')
q_id = $qwrap.data('q_id'),
val = $ch_box.val();
var dataToServer = {
q_id: q_id,
valueSelected: val
}
$.post('connect.php', dataToServer,function(){
var status=response.status
$qwrap.find('.status').text( status).addClass(status);
if( status=='correct'){
updateScore( response.points)
}
})
})
function updateScore( newScore){
var score= $points.data('score')+newScore;
$points.data('score',score).text( 'Score: '+score)
}
});
UPDATE:
Current code:
function update() {
var score = 0;
$('.queWrap').each(function(element) {
var $qwrap = $(element),
q_id = $qwrap.data('q_id'),
val = $qwrap.find('input:checked').val();
var dataToServer = {
q_id: q_id,
valueSelected: val
}
$.post('connect.php', dataToServer,function(response){
var status = response.status
$qwrap.find('.status').text(status).addClass(status);
if (status == 'correct'){
score += response.points;
$points.data('score', score).text('Score: ' + score);
}
})
});
}
...
//HTML
<div class="status"> </div>
Ok there is no errors but there is no marks appearing and calculating. Is it because of the connect.php I included in the javascript function. Do I need to navigate to page which connects to db connect.php or navigate to a page where it runs a query on finding answer marks for each selected answer? I am running out of time so can you please implement the code for me asap because I have to get this finished. I want the following to happen:
Count marks for each answer selected, if incorrect answer selected then value is 0 for those answers, if correct answer then it's marks are determined from database. Howcan I get each correct answer button to contain it's own answerId?
To determine answerId we can use the questionId displayed in text input (See PHP/HTML code snippet at top) and then depending on values of each answer button, retrieve the answerid matching the answer values for each question.
Below is example database showing Answer Table
AnswerId (auto PK) QuestionId Answer AnswerMarks
1 72 A 2
2 72 C 1
3 73 B 2
4 73 C 2
5 73 E 1
Your updateScore function works wrong. You should store the points for each question in a data element, and in the updateScore() function you should add all these up, and put the sum into the $points element. Something like this:
$(function() {
$('.queWrap .ck-button').change(function() {
update();
});
function update() {
var score = 0;
$('.queWrap').each(function(element) {
var $qwrap = $(element);
var q_id = $qwrap.data('q_id');
var val = $qwrap.find('input:checked').val();
var dataToServer = {
q_id: q_id,
valueSelected: val
};
$.post('connect.php', dataToServer, function(response){
var status = response.status
$qwrap.find('.status').text(status).addClass(status);
if(status == 'correct'){
score += response.points;
$points.data('score', score).text('Score: ' + score);
}
});
});
}
}
And this function should be invoked on every change of the answers. (I am not sure this works just an example).