PHP translation From SQL Database - javascript

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.

Related

How to execute JavaScript in PHP file executed from Ajax

I posted this earlier but it incorrectly got marked as a duplicate of Can scripts be inserted with innerHTML?, which isn't my problem. I'm not trying to run any JavaScript through using innerHTML, I'm trying to run JavaScript that is located in a PHP file called through Ajax/XmlHttp. I am using innerHTML in that JS, but I'm not writing more JS within that. So it's not a duplicate of that question and I'm trying it again now.
Not sure what's going on here. I'll explain the organization of my files first and then get into the code.
The application- Allows the user to select different attributes (i.e. year or name) and view pictures of matching results from a database.
Files- I have a gallery.php file that has a series of HTML form elements acting as selectors to get filtered results from a database. Whenever a selector is set or changed, the file sends a new request to a get.php file that uses Ajax to refresh the results without loading a new page. All that works great. My next task is to implement a modal section where I can click on an image and view a bigger version which I plan to do with JavaScript and CSS, but my intermediate goal is to just change some text at the bottom of the results from get.php again using JavaScript, just as a first step. But I can't seem to get any JavaScript written in get.php to fire.
Code-
This is gallery.php:
<?php
include_once("./../php/navbar.php");
?>
<html>
<head>
<link href="/css/siteTheme.css" rel="stylesheet">
<style>
.attributes span {
margin-right: 1rem;
}
</style>
<script>
function changeParams() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
}
};
year = document.getElementById("years_select").value;
nameFirst= document.getElementById("nameFirst_select").value;
/* Ton of other getElementById statements here that I'm excluding to keep things shorter */
url = "get.php?year="+year+......;
xmlhttp.open("GET", url, true);
xmlhttp.send();
} /* End function */
</script>
</head>
<body>
<div class="content">
<h1>Gallery</h1>
<form>Details:
<!-- -------------------- Year -------------------- -->
<select onchange="changeParams()" name="years" id="years_select">
<option value="All">Year</option>
<?php
include("/var/www/admin.php");
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$sql = "select year from db group by year order by year desc";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value=" . $row['year'] . ">" . $row['year'] . "</option>";
}
mysqli_close($conn);
?>
</select>
<!-- A bunch of other selectors are created here following the same pattern as above of getting results from a DB -->
<!-- -------------------- Searchbar -------------------- -->
<input type="text" size="50" onkeyup="changeParams()" name="search" id="search" placeholder="Search"></input>
</form>
<div id="test">Choose some filters to see some results!</div>
</form>
</div> <!-- Ends content div -->
</body>
</html>
This is get.php:
<html>
<head>
<style>
/* Bunch of CSS that's not relevant here */
</style>
<script type="text/javascript">
console.log(".....");
var parts = document.querySelectorAll("div.imgContainer");
console.log("Found something:", parts);
parts.addEventListener("click", function(){
document.getElementById("anID").innerHTML = "Test...";
});
</script>
</head>
<body>
<?php
include("/var/www/admin.php");
$year = $_GET['year'];
//Bunch of other variables set here following the same logic, getting data from gallery.php
$conn = mysqli_connect($dbServername, $publicdbUsername, $publicdbPass, $dbName);
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
echo '$conn';
}
$sql = 'select * db';
/* ---------- Creating SQL statement ---------- */
$clauses = 0;
if ($year != "All") {
if ($clauses == 0) {
$sql = $sql . ' where year = "' . $year . '" and';
$clauses = $clauses + 1;
} else {
$sql = $sql . ' year = "' . $year . '" and';
}
} /* Bunch of other if statements to get set information and add to sql statement as such */
// Need to chop of the last ' and' from the sql statement
$sql = substr($sql, 0, -4);
$sql = $sql . ' order by year desc';
$result = mysqli_query($conn, $sql);
$num_results = mysqli_num_rows($result);
if ($num_results == 0 or $clauses == 0) {
echo "<p>No matches to your query. Try refining your search terms to get some results.</p>";
} else {
echo "<p>" . $num_results . " results matched your query.</p>";
echo "<div class=results>";
//echo "<div>";
echo '<script type="text/javascript">
function modalFunction() {
document.getElementById("anID").innerHTML = "test";
}
</script>';
while ($row = mysqli_fetch_array($result)) {
$pic = $row['pathToPic'];
$wwwImg = substr($pic, 13);
//echo "<span id=aCard><img src=" . $wwwImg . " height ='250px'>";
//echo "<span class=text>" . $row['fullCardInfo'] . "</span></span>";
echo "<div class=fullContainer><div class='imgContainer'><img class=image src=" . $wwwImg ."></div><p class=text>" . $row['fullInfo'] . "</p></div>";
} // End while of results
echo "</div>";// End results div//</div>";
//echo '<div class="modal"><p id="anID"></p></div>';
} // End else of "if results"
mysqli_close($conn);
?>
<script>
</script>
<div>
<p id="anID">This in a div</p>
</div>
<!--<span>
<p id="anID">This in a span</p>
</span>-->
</body>
</html>
Sorry if that was messy, I chopped out a bunch of stuff that just gets/selects/filters some data. All that works and all variables that are left in there are set in my full code.
But the issue I'm having is writing JavaScript in get.php to change the text in the <p id="anID"> tags. I've tried JS in a few different areas of get.php, from in the <head> tags, to echoing it in <script> tags in the PHP, to pure <script> tags after the PHP statements are done (I think I left them in a few different places).
Problem is that nothing I do works to change the text in the <p> tags I references. Additionally, the console.log statements in the header of get.php don't seem to get called either. They don't fire no matter where I place them in get.php. Console.log works fine in gallery.php so it's not some issue with my browser or anything.
Long term, I will be adding JS query selectors to bring up a bigger image when an image is clicked on, but for now I'm just trying to make ANY JavaScript work in get.php and I'm struggling to do so. I don't see how this is a duplicate of the suggested repeat as I'm not trying to run JavaScript through innerHTML here.
Scratch that, it actually is trying to pass JavaScript through innerHTML as the information from get.php comes from this section of gallery.php:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
console.log("Response: ", this.responseText);
}
So it appears this is a duplicate of the question I linked after all. Apologies. However, there are not great answers to that question, so any tips would be appreciated.
This line:
document.getElementById("test").innerHTML = this.responseText;
Is simply going to add the contents of this.responseText to the element test. I'm sure you understand that much, but what you want to do is completely wrong. The scripts within the output of get.php will NOT be executed at all and you have corrupted your HTML as well by including a second <html><head> and more.
A better approach would be if get.php returned the data from you DB query as a JSON string like so:
$data;
while ($row = mysqli_fetch_array($result)) {
$data[]['pic'] = $row['pathToPic'];
$data[]['wwwImg'] = substr($row['pathToPic'], 13);
}
echo json_encode($data);
exit;
And then back on gallery.php you do something like:
if (this.readyState == 4 && this.status == 200) {
formatResult(this.responseText);
}
// ... snip ...
function confirmJson(str) {
var j = null;
if (str) {
try { j = JSON.parse(str); }
catch (e) { j = null; }
}
return j;
}
function formatResult(str) {
var data = confirmJson(str);
if (! data) {
console.log("result is not JSON");
return;
}
// do stuff with the data
var i, max = data.length;
var h = document.createElement("div");
var img;
for(i=0;i<max;i++) {
img = document.createElement("src");
img.src = data[i].wwwImg;
img.addEventListener("click",function(){ alert("pic:["+ data[i].pic +"]"); },true);
h.appendChild(img);
}
document.getElementById("test").innerHTML = h;
}

Json.parse() behaves differently with apparently the same input from 2 different pages php

It's the first time that i ask something here, but this problem seems to me too strange and i have to do it.
I had a php code like this:
//Here i take from $_GET
if(isset($_GET["one"])){
$one= $_GET["one"];
}
if(isset($_GET["two"])){
$two= $_GET["two"];
}
if(isset($_GET["three"])){
$three= $_GET["three"];
}
//Here i process each variable for the query i want
if($one== "any"){
$one= "%";
}
else $one= "%".$one."%";
if($two== "any"){
$two= "%";
}
else $two= $two."%";
if($three== "any"){
$three= "%";
}
//
$query = "SELECT one, two, three FROM TABLE WHERE one LIKE ? AND two LIKE ? AND three LIKE ?"
//Here i put "manually" each variable in $params
$params = [];
$params_type = "sss";
$params[0] = $one;
$params[1] = $two;
$params[2] = $three;
echo json_encode(exec_query_header_params($query, $params_type, $params));
For future necessity i wanted to make it more dynamic and I rewrote it like this:
$i=0;
$params = [];
$params_type = "sss";
foreach ($_GET as $key => $value) {
if(isset($value)){
if($value == "any")
$params[$i] = "%";
else{
if($key == "one")
$params[$i] = "%".$value."%";
elseif($key == "two")
$params[$i] = $value."%";
else
$params[$i] = $value;
}
}
$i++;
}
echo json_encode(exec_query_header_params($query, $params_type, $params));
Now, the strange thing is that the codes apparently gives me in output the same array, something like this:
[["one","two","three"], //the table-head
,["aaa","bbb","ccc"], /*
,["aaa","bab","cbc"], the table-body
,["aaa","bgb","cgc"]] */
But this ajax request works only with the old code:
var query = 'getter.php?one='+one+'&two='+two+'&three='+three;
$.ajax({type:'GET', url:query, success:takeFromJSON, cache:false, async:false});
//(Inside takeFromJSON there is a call to JSON.parse(data);)
Can anybody explain to me why this happens?

How to use javascript if statements within function to populate table

I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}

PHP to Jquery through json ruins array

I'm trying to perform some PHP code and then pass it's results to another PHP script through jquery.
One of these results is an array, and I'm passing it to a GET so it gets to the other script. (alot of work, but I can't have page reloads even tho I have to use PHP).
The problem occurs when I'm trying to put the PHP variable through JQuery.
What I have to do this for me is:
var _leafs = <?php echo json_encode($leafs); ?>;
When I run json_encode on $leafs and then print the result (all using PHP), it gives me a json array that has been successfully validated by JSONLint.
When I use the above code and alert() the result it's missing the brackets and quotes.
Even weirder is when I pass it through like so:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
The result is this:
" string(4) "
"
Which shows up to be a <br> in my html reader.
Am I missing something when I'm converting it to json?
Additional code:
<?php
// Fetch the XML from the URL
if (!$xml = file_get_contents($_GET['url'])) {
// The XML file could not be reached
echo 'Error loading XML. Please check the URL.';
} else {
// Get the XML file
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$paths = [];
$leafs = [];
foreach ($xpath->evaluate('//*|//#*') as $node) {
$isLeaf = !($xpath->evaluate('count(#*|*) > 0', $node));
$path = '';
foreach ($xpath->evaluate('ancestor::*', $node) as $parent) {
$path .= '/'.$parent->nodeName;
}
$path .= '/'.($node instanceOf DOMAttr ? '#' : '').$node->nodeName;
if ($isLeaf) {
$leafs[$path] = TRUE;
} else {
$paths[$path] = TRUE;
}
}
$paths = array_keys($paths);
$leafs = array_keys($leafs);
echo "Choose a path<br><br>
<form>
<select id='field_dropdown'>";
foreach($paths as $value) {
echo "<option value='".$value."'>".$value."</option>";
}
echo " </select>
<button id='send_path'>Send path</button>
</form>
";
}
?>
<script>
$(document).ready(function() {
$('#send_path').click(function() {
var _path = $("#field_dropdown").val();
// Get the leafs array and send it as a json string to set_fields.php
var _leafs = <?php echo json_encode($leafs); ?>;
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, function(data) {
$('#fields').append(data);
}).error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
return false;
});
});
</script>
And here the code where I want the json array to end up (and then get turned back into a PHP array).
<?php
// Match all the fields to the values
$path = $_GET['pt'];
$leafs = json_decode($_GET['lf']);
$fieldLeafs = [];
$pathLength = strlen($path) + 1;
foreach ($leafs as $leaf) { if (0 === strpos($leaf, $path.'/')) { $fieldLeafs[] = substr($leaf, $pathLength); } }
var_dump($path."<br>");
var_dump($leafs."<br>");
?>
What if you get the array through jquery instead of echoing it?
<input id="hidden-value" value="<?php echo json_encode($leafs); ?>" />
and then
var _leafs = $('#hidden-value').val();
What about adding an = after the lf query parameter when you build the get URI?
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, ...
Just write 'json' in the last parameter of get method:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
$('#fields').append(data);
},'json')//<-- this
.error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
Did you try this?
var _leafs = [<?php foreach($leafs as $leaf){ echo "'$leaf',"; } ?>]

issues with ajax and javascript when trying to count marks

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).

Categories

Resources