I am making a MEAN stack application. It is an online live test taking application where user has to face a multiple choice question with 4 options and has to choose one.
Now, the problem i'm getting is, suppose there are 2 questions:
1. What is 1+0?
a. 1
b. 3
c. 4
d. 5
The answer to this question is at index 1,also the answer is 1. So my controller is sending 1 to the Submit button(it's sending the index, not the actual answer).
Take another question. What is 3+4?
a. 7
b. 8
c. 9
d. 10
Here, the controller sends 1 to the database, as the correct answer marked by user is at first index.
I want it to send 7.
This is my controller
liveController.js
examApp.controller('liveController', ['$scope', '$filter', '$http', '$location', '$routeParams', 'queryService', 'authenticationService', function($scope, $filter, $http, $location, $routeParams, queryService, authenticationService) {
var main = this;
var totalnoofQuestions;
var user;
main.questionsforTime = [];
this.getsecurityQuestion = function() {
var data = {
_id: $routeParams.userId
}
queryService.getsecurityQuest(data)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
} else {
var userId;
var data = response.data.data;
main.user = data.name;
main.userId = data._id;
authenticationService.setToken(response.data.token);
}
}, function errorCallback(response) {
alert("There was a problem.");
})
}
this.getsecurityQuestion();
this.logged = function() {
main.username = queryService.userName;
if (queryService.log == 1 || queryService.userId !== 'undefined') {
return 1;
} else {
$location.path('/');
}
}
this.logged();
this.userId = $routeParams.userId;
main.heading = "Welcome To Exam App";
$('.thisismodalforlivetestwarning').modal('show');
$(document).on('click', '#returntotaketest', function() {
$('.thisismodalforlivetestwarning').modal('hide');
location.replace("#/taketheTest/" + main.userId);
})
this.getasingleTest = function() {
var singletestId = $routeParams.testId;
queryService.getasingleTest(singletestId)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
window.location.href = "#/taketheTest/" + main.userId;
} else {
if (response.data.data.questions.length == 0) {
$location.path("/taketheTest/" + main.userId);
alert("No questions present.");
} else {
main.totalnoofQuestions = response.data.data.questions.length;
main.questionsforTime.push(response.data.data.questions.length);
main.testHeading = "Test topic is " + response.data.data.testName;
main.singletestArray = response.data.data.questions;
main.time = response.data.data.testDuration;
}
}
}, function errorCallback(response) {
alert("There was a problem.");
})
}
this.getasingleTest();
var totalSeconds = 300;
var minutes = parseInt(totalSeconds / 60);
var seconds = parseInt(totalSeconds % 60);
this.theTime = function() {
totalSeconds = totalSeconds - 1;
minutes = parseInt(totalSeconds / 60);
seconds = parseInt(totalSeconds % 60);
main.timetakeninTest = (300 - totalSeconds);
document.getElementById('test-time-left').innerHTML = 'Time Left: ' + minutes + ' minutes ' + seconds + ' seconds';
if (totalSeconds <= 0) {
clearTimeout(main.counttime);
main.timetakeninTest = 300;
alert("Time Is Up!!");
container.style.display = 'none';
var testattemptData = {
testgivenBy: main.user + " " + $routeParams.userId,
testId: $routeParams.testId
}
queryService.testAttemptedBy(testattemptData)
.then(function successCallback(response) {}, function errorCallback(response) {})
var data = {
userid: $routeParams.userId,
testid: $routeParams.testId,
score: score,
timeTaken: main.timetakeninTest,
totalCorrect: (score / 10),
totalIncorrect: (10 - (score / 10))
}
queryService.submitTest(data)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
} else {
main.performanceUserID = response.data.data.user;
main.answerscorrect = response.data.data.totalCorrect;
main.answerswrong = response.data.data.totalIncorrect;
main.madeScore = response.data.data.score;
main.timeTaken = response.data.data.timeTaken;
$('.thisismodalforUserTestPerformance').modal('show');
}
}, function errorCallback(response) {
alert("There was a problem.");
})
}
}
var currentQuestion = 0;
var score = 0;
var totalQuestionAsked = 0;
var container = document.getElementById('quizContainer');
var questionEl = document.getElementById('question');
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
var nextButton = document.getElementById('nextButton');
var resultCont = document.getElementById('result');
this.loadQuestion = function(questionIndex) {
if (questionIndex == 0) {
totalQuestionAsked = main.totalnoofQuestions;
$('.thisismodalforlivetestwarning').modal('hide');
main.counttime = setInterval(this.theTime, 1000);
}
var q = main.singletestArray[questionIndex];
questionEl.textContent = (questionIndex + 1) + '.' + q.question;
opt1.textContent = q.optionA;
opt2.textContent = q.optionB;
opt3.textContent = q.optionC;
opt4.textContent = q.optionD;
};
this.nextQuestion = function() {
var selectedOption = document.querySelector('input[type=radio]:checked');
if (!selectedOption) {
alert("Select An Answer First.");
return;
}
var answer = selectedOption.value; //This line
console.log("this is problem " + answer);
if (main.singletestArray[currentQuestion].answer == answer) {
score += 10;
}
var data = {
userid: $routeParams.userId,
testid: $routeParams.testId,
questionid: main.singletestArray[currentQuestion]._id,
userAnswer: answer,
correctAnswer: main.singletestArray[currentQuestion].answer,
timetakenInsecs: main.timetakeninTest
}
queryService.submitAnswer(data)
.then(function successCallback(response) {}, function errorCallback(response) {})
selectedOption.checked = false;
currentQuestion++;
if (currentQuestion == totalQuestionAsked - 1) {
nextButton.textContent = 'Finish';
}
if (currentQuestion == totalQuestionAsked) {
container.style.display = 'none';
clearTimeout(main.counttime);
var testattemptData = {
testgivenBy: main.user + " " + $routeParams.userId,
testId: $routeParams.testId
}
queryService.testAttemptedBy(testattemptData)
.then(function successCallback(response) {}, function errorCallback(response) {})
var data = {
userid: $routeParams.userId,
testid: $routeParams.testId,
score: score,
timeTaken: main.timetakeninTest,
totalCorrect: (score / 10),
totalIncorrect: (10 - (score / 10))
}
queryService.submitTest(data)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
} else {
main.performanceUserID = response.data.data.user;
main.answerscorrect = response.data.data.totalCorrect;
main.answerswrong = response.data.data.totalIncorrect;
main.madeScore = response.data.data.score;
main.timeTaken = response.data.data.timeTaken;
$('.thisismodalforUserTestPerformance').modal('show');
}
}, function errorCallback(response) {
alert("There was a problem");
})
return;
}
this.loadQuestion(currentQuestion);
}
}]);
<link rel="stylesheet" href="../css/livetest.css">
<!-- W3 schools styles-->
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">
<div ng-controller="liveController as live">
<nav class="navbar fixed-top navbar-toggleable-md navbar-inverse bg-inverse">
<br/>
<div class="container">
<a class="navbar-brand" href="">
<h2>
<i class="fa fa-line-chart" aria-hidden="true"></i> Exam App Dashboard
</a>
</div>
<br/>
</nav>
<div Style="color:white;font-weight:bold;font-size:2em; text-align:center;" id="test-time-left"></div>
<div style="background: #F2F2F2;" id="quizContainer" class="container">
<div class="title" style="text-align: center; font-weight:bold; font-size: 1.5em;">{{live.testheading}}</div>
<div id="question" class="question" style="font-size: 2em; font-weight: bold;"></div>
<label class="option">
<input type="radio" name="option" value="1" />
<span id="opt1"></span>
</label>
<label class="option">
<input type="radio" name="option" value="2" />
<span id="opt2"></span>
</label>
<label class="option">
<input type="radio" name="option" value="3" />
<span id="opt3"></span>
</label>
<label class="option">
<input type="radio" name="option" value="4" />
<span id="opt4"></span>
</label>
<button id="nextButton" class="next-btn" ng-click="live.nextQuestion()">Next Question </button>
</div>
<br/>
<!-- Place to keep all the modals -->
<!-- Modal -->
<div class="modal fade thisismodalforlivetestwarning" id="modalfortestwarning" role="dialog" data-backdrop="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div style="background-color: #4CAF50;" class="modal-header">
<h4 align="center" class="modal-title">
<span style="color:white;">: Please Read The instructions Carefully :</span>
</h4>
</div>
<div class="modal-body">
<ol>
<li>You will be alloted 5 Minutes to Give Test, After which window will close Automatically.</li>
<li>You can't go back after submitting the Answer for each Question.</li>
<li>you can submit the Test before the finishing Time if you want but can't after the time finishes, It will Automatically be submitted.</li>
<li>Please don't do cheating in test. Be fair to yourself for your true Assessment of skills.</li>
<li>If you aggree with all the terms stated above you may proceed by clicking Start Button Below.</li>
</ol>
<h3 align="center">
<strong>
<em>Best Of Luck!</em>
</strong>
</h3>
</div>
<div style="background-color: #404549;" class="modal-footer">
<button type="button" class="btn btn-success" ng-click="live.loadQuestion(0)">Start!</button>
<button type="button" class="btn btn-danger" id="returntotaketest">Return</button>
</div>
</div>
</div>
</div>
<!-- MOdal for User Performance -->
<!-- Modal -->
<div class="modal fade thisismodalforUserTestPerformance" role="dialog" data-backdrop="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div style="background-color: #4CAF50;" class="modal-header">
<h4 align="center" class="modal-title">
<span style="color:white;">: Your Score Card for the Test :</span>
</h4>
</div>
<div class="modal-body">
<div style="background-color: #404549;" class="modal-body">
<a class=" list-group-item">User ID: {{live.performanceUserID}}</a>
<a class=" list-group-item">Total Correct Answers: {{live.answerscorrect}}</a>
<a class=" list-group-item">Total Wrong Answers: {{live.answerswrong}}</a>
<a class=" list-group-item">Score Secured: {{live.madeScore}}</a>
<a class=" list-group-item">Total Time Taken: {{live.timeTaken}} Seconds</a>
</div>
<h3 align="center">
<strong>
<em>Thank You! For giving the Test...</em>
</strong>
</h3>
</div>
<div style="background-color: #404549;" class="modal-footer">
<button type="button" class="btn btn-danger" id="returntotaketest">Return</button>
</div>
</div>
</div>
</div>
The action happens at nextQuestion function at the commented line (commented with '//This line'). I have tried my best to explain my problem and can upload more code if required.
Any help will be appreciated.
You could do something like this
var selectedOption = document.querySelector('input[type=radio]:checked');
if (!selectedOption) {
alert("Select An Answer First.");
return;
}
//As selectedOption is actually an index we can use it to get the answer
var answerValue = document.getElementById('opt'+ selectedOption);
var answer = answerValue.textContent;
Related
I want to create a chat system (which i already accomplished), but a working username selector, and it gets the username in the input, then when the user sends a message via chat, it is their username!! And also, i tried putting it in a localStorage, so when the user refreshes or rejoins, the name is still there and not removed! I think im close, but it says UNDEFINED, which really got me confused? Please help? Thanks!!
localStorage.playerusername = document.querySelector(".hud-name").value;
let username = localStorage.playerusername;
let chatMsg = [];
function appendChatMessage(currentUserName, chatMessage) {
let chatElem = document.createElement("p");
chatElem.innerHTML = "<strong>" + currentUserName + ": </strong>" + chatMessage;
document.querySelector(".chat").appendChild(chatElem);
}
for (let i = 0; i < chatMsg.length; i++) {
appendChatMessage(username, chatMsg[i])
}
let Game = {
currentGame: {
variables: {
sendMessage: function(messageContent) {
chatMsg.push(messageContent);
appendChatMessage(username, messageContent);
document.querySelector(".enterT").innerHTML = ""
},
addChatTopRemoverPackage: async function() {
if (chatMsg.length == 7) {
let chatElem = document.querySelector(".chat")
if (chatElem.children[0]) {
chatElem.removeChild(chatElem.children[0])
if (chatMsg.length > 0) {
chatMsg.shift()
//if (chatMsg.length == 0) {
//chatMsg.pop();
//}
}
}
}
},
chatRemoverRefresher: setInterval(() => {
Game.currentGame.variables.addChatTopRemoverPackage()
}, 0.000000000001)
}
}
}
HTML:
<div class="hud-name-select
type-text
maxlength-16
">
<input class="hud-name" type="text" maxlength="16" placeholder="Enter Nickname...">
<div></div>
<div><br></div>
<button class="btn-play btn-green background-color-green">
<div style="
display: none;
" display="none">Loading......<div></div>
</div>
<span>Play</span>
</button>
</div>
</div>
</div>
<div class="msgcont">
<div class="messages">
<h1>
CHAT
</h1>
<div class="chat">
</div>
<div>
<input class="enterT" type="text" placeholder="Enter A Message..!"><button
onclick="Game.currentGame.variables.sendMessage(document.querySelector('.enterT').value)">send
message</button>
</div>
<br>
</div>
</div>
Kevin
Hi I'm trying to get my SQL database to update with user input via my HTML form that was displayed from my javascript file. Help is very appreciated :)
index.html
Display Events (HTML)
<!---- My Events ---->
<div id="my_events" class="menu_link">
<br>
<nav class="clean">
<div class="nav-wrapper">
<div class="col s12">
Home
My Events
</div>
</div>
</nav>
<div class="row">
<div class="col s12">
<h4>My Events</h4>
<button onclick="displayEvents(); loadPage()" class="waves-effect waves-light btn indigo">Display
Events</button>
<!-- Preloader -->
<div class="loadprogress indigo darken-4" style="width: 100%">
<div class="runningbar indigo lighten-1"></div>
</div>
<div class="content">
<!-- Table container -->
<table>
<!-- <th>Event ID</th> -->
<th>Event ID</th>
<th>Event Name</th>
<th>Event Description</th>
<th>Event Category</th>
<th>Event Address</th>
<th>Event Location</th>
<th>Event Date</th>
<th>Event Time</th>
<table id="eventsTable" class="striped">
<!-- List user events -->
</table>
</table>
</div>
</div>
</div>
</div>
Update Events Modal (HTML)
<!---- Update Event Section ---->
<!-- Modal Structure -->
<div id="update_events" class="modal">
<h5 class="modal-close right" onclick="closeModal()">✕</h5>
<div class="modal-content">
</div>
</div>
script.js
Display Events Fetch (JavaScript)
/* - Display Events - */
function displayEvents() {
loadPage();
// Define output string that will display the database data
var outStr = '';
var outStr2 = '';
fetch('api/ws.php?action=displayEvents', {
method: "GET",
credentials: "include",
})
.then(function (response) {
loadPage();
response.json().then(function (data) {
localStorage.setItem("events", JSON.stringify(data));
// console.log(data);
data.forEach(row => {
outStr +=
'<tr><td>' + row.eventID +
'</td><td>' + row.eventName +
'</td><td>' + row.eventDescription +
'</td><td>' + row.eventCategory +
'</td><td>' + row.eventAddress +
'</td><td>' + row.eventLocation +
'</td><td>' + row.eventDate +
'</td><td>' + row.eventTime +
'</td><td><button href="#update_events" class="modal-trigger" onclick="fillUpdate(' + row.eventID + ')" value="' + row.eventID + '"><i class="material-icons">edit</i></button>' +
'</td><td>' + '<button onclick="deleteRemoveEvent(' + row.eventID + ')" value="' + row.eventID + '"><i class="material-icons">delete</i></button>' +
'</td></tr>';
outStr2 =
`<div>
<h4>Update Events</h4>
<form action="api/ws.php" method="POST" onclick="return preventDefault()" novalidate>
<div class="input-field">
<i class="material-icons prefix">title</i>
<input id="update_ev_name" name="update_ev_name" placeholder="Event Name" type="text">
</div>
<div class="input-field">
<i class="material-icons prefix">notes</i>
<textarea id="update_ev_desc" name="update_ev_desc" class="materialize-textarea"
placeholder="Event Description"></textarea>
</div>
<div class="input-field">
<i class="material-icons prefix">category</i>
<input type="text" id="update_ev_cat" name="update_ev_cat" placeholder="Enter Your Event Type">
</div>
<div class="input-field col s6">
<i class="material-icons prefix">map</i>
<input type="text" id="update_ev_address" name="update_ev_address" placeholder="Enter Your Address">
</div>
<div class="input-field col s6">
<i class="material-icons prefix">flag</i>
<input type="text" id="update_ev_loc" name="update_ev_loc" placeholder="Event Location">
</div>
<div class="input-field col s6">
<i class="material-icons prefix">date_range</i>
<input type="text" id="update_ev_date" class="datepicker" placeholder="Event Date">
</div>
<div class="input-field col s6">
<i class="material-icons prefix">schedule</i>
<input type="text" id="update_ev_time" class="timepicker" placeholder="Event Time">
</div>
<input type="hidden" name="eventid" value="`+ row.eventID +`" id="eventid">
<input type="hidden" name="action" value="update" id="updateEvent">
<button class="btn waves-effect waves-light" type="submit" onclick="postUpdateEvent(`+ row.eventID +`)">Update
Event</button>
</form>
</div>`
});
document.getElementById('eventsTable').innerHTML = outStr;
document.getElementById('update_events').innerHTML = outStr2;
});
});
}
Autofill Update Form (JavaScript)
/* - Autofill Update Form - */
function fillUpdate(eventid) {
console.log("Fill event with id " + eventid);
events = JSON.parse(localStorage.getItem("events"));
// console.log(events);
selectedEvent = events.filter(event => event[0] == eventid)[0];
if (selectedEvent != null) {
console.log(selectedEvent);
document.getElementById("update_ev_name").value = selectedEvent[1];
document.getElementById("update_ev_desc").value = selectedEvent[2];
document.getElementById("update_ev_cat").value = selectedEvent[3];
document.getElementById("update_ev_address").value = selectedEvent[4];
document.getElementById("update_ev_loc").value = selectedEvent[5];
document.getElementById("update_ev_date").value = selectedEvent[6];
document.getElementById("update_ev_time").value = selectedEvent[7];
// document.getElementById("eventid").value = selectedEvent[8];
}
}
Update Events Function with Fetch (JavaScript)
/* - Update Events - */
function postUpdateEvent(eventid) {
console.log("Update event with id " + eventid);
events = JSON.parse(localStorage.getItem("events"));
selectedEvent = events.filter(event => event[0] == eventid)[0];
var eventid = "eventid";
if (selectedEvent != null) {
console.log(selectedEvent);
document.getElementById("update_ev_name").value = selectedEvent[1];
document.getElementById("update_ev_desc").value = selectedEvent[2];
document.getElementById("update_ev_cat").value = selectedEvent[3];
document.getElementById("update_ev_address").value = selectedEvent[4];
document.getElementById("update_ev_loc").value = selectedEvent[5];
document.getElementById("update_ev_date").value = selectedEvent[6];
document.getElementById("update_ev_time").value = selectedEvent[7];
// document.getElementById("eventid").value = selectedEvent[8];
}
var userUpdate = {
'update_ev_name': document.getElementById("update_ev_name").value,
'update_ev_desc': document.getElementById("update_ev_desc").value,
'update_ev_cat': document.getElementById("update_ev_cat").value,
'update_ev_address': document.getElementById("update_ev_address").value,
'update_ev_loc': document.getElementById("update_ev_loc").value,
'update_ev_date': document.getElementById("update_ev_date").value,
'update_ev_time': document.getElementById("update_ev_time").value
}
// var updatefd = new FormData();
// updatefd.append('action', 'update');
// updatefd.append('eventid', eventid.value);
// updatefd.append('update_ev_name', update_ev_name.value);
// updatefd.append('update_ev_desc', update_ev_desc.value);
// updatefd.append('update_ev_cat', update_ev_cat.value);
// updatefd.append('update_ev_address', update_ev_address.value);
// updatefd.append('update_ev_loc', update_ev_loc.value);
// updatefd.append('update_ev_date', update_ev_date.value);
// updatefd.append('update_ev_time', update_ev_time.value);
// updatefd.append('updateEvent', updateEvent.value);
fetch('api/ws.php?action=updateEvent', {
method: "POST",
body: JSON.stringify(userUpdate),
credentials: 'include',
// body: updatefd,
})
// Force error into console
.then(function (response) {
response.text().then(function (text) {
console.log(text);
});
// HTTP Response Codes
if (response.status === 200) {
// loadPage();
console.log(eventid.value);
}
if (response.status === 202) {
console.log('Update Successful');
}
if (response.status === 400) {
errormessage('Error: Bad Request');
console.log('Bad Request');
console.log(eventid.value);
return;
}
if (response.status === 401) {
console.log('Not permitted');
return;
}
if (response.status === 501) {
errormessage('Error: Not implemented');
console.log('Not implemented :(');
return;
}
response.text().then(function (text) {
console.log(text);
});
});
}
ws.php
Switch Case API (PHP)
/* - Display User Events - */
case "displayEvents":
// if ($_SESSION['se']->is_logged_in()) {
$result = $db->displayEvents();
if ($result == false) {
http_response_code(501);
} else {
http_response_code(202);
echo json_encode($result);
}
// } else {
// http_response_code(401);
// }
break;
/* - Autofill the update form - */
case "fillUpdate":
if (isset($_POST["action"])) {
$result = $_SESSION['se']->is_logged_in();
if ($result == true) {
$evid = $_POST['evid'];
$details = $db->get_details($evid);
if ($details == false) {
http_response_code(501);
} else {
http_response_code(201);
echo json_encode($details);
}
}
}
break;
/* - Update the User Event - */
case "updateEvent":
if (isset($_POST["action"])) {
// $evid = $_GET['evid'];
$_SERVER['REQUEST_METHOD'] == 'POST';
$objreg = json_decode(file_get_contents("php://input"), true);
$evid = testInput($objreg['evid']);
$update_ev_name = testInput($objreg['update_ev_name']);
$update_ev_desc = testInput($objreg['update_ev_desc']);
$update_ev_cat = testInput($objreg['update_ev_cat']);
$update_ev_address = testInput($objreg['update_ev_address']);
$update_ev_loc = testInput($objreg['update_ev_loc']);
$update_ev_date = testInput($objreg['update_ev_date']);
$update_ev_time = testInput($objreg['update_ev_time']);
$db->updateEvent($evid, $update_ev_name, $update_ev_desc, $update_ev_cat, $update_ev_address, $update_ev_loc, $update_ev_date, $update_ev_time);
// echo "Record updated successfully";
http_response_code(202);
} else {
http_response_code(400);
}
// if ($_POST["eventid"] == null)
break;
db.php
Database Functions (PHP + SQL)
/* -- Display Events Function -- */
function displayEvents()
{
db_connection();
try {
$stmt = $this->dbconn->prepare('SELECT eventID, eventName, eventDescription, eventCategory, eventAddress, eventLocation, eventDate, eventTime FROM events');
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
} catch (PDOException $ex) {
throw $ex;
}
}
/* - Autofill the Update Event Form - */
function get_details($evid)
{
$stmt = $this->dbconn->prepare("SELECT * FROM events WHERE eventID = :eid");
$stmt->bindValue(":eid", $evid);
$stmt->execute();
$result = $stmt->fetch();
return $result;
}
/* -- Update Events Function -- */
public function updateEvent($evid, $update_ev_name, $update_ev_desc, $update_ev_cat, $update_ev_address, $update_ev_loc, $update_ev_date, $update_ev_time)
{
print_r("hello");
db_connection();
try {
$this->dbconn->beginTransaction();
/* --- Event Table --- */
$stmt = $this->dbconn->prepare("UPDATE events SET eventName = :update_ev_name, eventDescription = :update_ev_desc, eventCategory = :update_ev_cat, eventAddress = :update_ev_address, eventLocation = :update_ev_loc, eventDate = :update_ev_date, eventTime = :update_ev_time WHERE eventID = :eid");
// bind values
$stmt->bindValue(":eid", $evid);
$stmt->bindValue(':update_ev_name', $update_ev_name);
$stmt->bindValue(':update_ev_desc', $update_ev_desc);
$stmt->bindValue(':update_ev_cat', $update_ev_cat);
$stmt->bindValue(':update_ev_address', $update_ev_address);
$stmt->bindValue(':update_ev_loc', $update_ev_loc);
$stmt->bindValue(':update_ev_date', $update_ev_date);
$stmt->bindValue(':update_ev_time', $update_ev_time);
// Execute the update statement
$stmt->execute();
// Commit changes here
$this->dbconn->commit();
} catch (PDOException $ex) {
$ex->getMessage();
exit();
}
}
Errors I'm getting :( and no respose/preview errors in network tab
Having issue when i am using fileupload object to show the files while before upload in the modal
Even Try make a shallow copy of DOM object to use it but it still not working
Kindly Give me a possible solution for this problem
HTML and javascript Kindly see the FileConfigHandler Method
<div id="filedata"></div>
<div class="col-md-9">
<div class="homepage_contant">
<div class="container">
<!-- Start File Upload Section -->
<h4>File Upload</h4>
<form id="drag-and-drop-zone" class="upload_container" action="/Home/Upload" method="POST" enctype="multipart/form-data" ondrop="dropHandler(event);">
<div class="text-center">
<img class="cloud_upload_img" src="~/Content/images/cloud.png" />
<p>Drag & Drop Files Here or <span class="browse_btn_holder">Browse <input class="browse_btn" type="file" accept=".xls..xlsx image/* " multiple id="mfile" name="mfile" title='Click to add Files' /> </span> to upload files</p>
</div>
<!-- Modal -->
<div class="upload_file_modal modal" id="uploadFileModal" tabindex="-1" role="dialog" aria-labelledby="uploadFileModal" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">File Upload</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="container">
<ul class="list-unstyled p-2 d-flex flex-column col" style="padding:0 !important" id="files">
<li class="text-muted text-center empty"><p id="txt"> Files has been seleted. </p></li>
</ul>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="upload_field_wrap">
<label for="ItemTitle"> File Title</label>
<input type="text" class="form-control" id="title" name="title" />
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
#Html.DropDownList("Department", ViewBag.lst as SelectList, "Select Department", new { #class = "form-control" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
<select class="form-control" id="CourseId" name="CourseId">
<option value="" disabled selected>Course</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
<select class="form-control" id="category" name="category">
<option value="" disabled selected>Select Category</option>
<option value="mid">
Mid Term
</option>
<option value="final">
Final
</option>
<option value="quiz">
Quiz
</option>
<option value="summary">
Summary
</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
<select id="yearOfPublish" name="yearOfPublish" class="form-control">
<option value="" disabled> Select Year</option>
#for (int i = 2000; i < 2020; i++)
{
<option value="#i">#i</option>
}
</select>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<div class="upload_field_wrap">
<label for="description">Description</label>
<textarea class="form-control" id="" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
<!-- End File Upload Section -->
#section scripts
{
<script src="~/Scripts/jquery.dm-uploader.min.js"></script>
<script src="~/Scripts/upload_file_ui.js"></script>
<script>
function dropHandler(event) {
event.preventDefault();
mfile.files = event.dataTransfer.files;
console.log(mfile);
//ChangeImageHandler();
FileConfigHandler();
}
function formatBytes(bytes, decimals) {
if (bytes == 0) return '0 Bytes';
var k = 1024,
dm = decimals <= 0 ? 0 : decimals || 2,
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
function ChangeImageHandler()
{
var x = $('#mfile').val();
let file = $('#mfile')[0].files[0];
var size = $('#mfile')[0].size;
var sizeWithTag = formatBytes(size);
$('#item_size').text(sizeWithTag);
$('#item_title').text(file.name);
if (x.split('.').pop()=='pdf') {
$("#item_type_img").attr("src", "../../Content/images/files_types/pdf.png");
}
else if (x.split('.').pop() == 'docx') {
$("#item_type_img").attr("src", "../../Content/images/files_types/doc.png");
}
else if (x.split('.').pop() == 'jpg') {
$("#item_type_img").attr("src", "../../Content/images/files_types/jpg.png");
}
else if (x.split('.').pop() == 'png') {
$("#item_type_img").attr("src", "../../Content/images/files_types/png.png");
}
else if (x.split('.').pop() == 'ppt') {
$("#item_type_img").attr("src", "../../Content/images/files_types/ppt.png");
}
else if (x.split('.').pop() == 'txt') {
$("#item_type_img").attr("src", "../../Content/images/files_types/txt.png");
}
else if (x.split('.').pop() == 'xls') {
$("#item_type_img").attr("src", "../../Content/images/files_types/xls.png");
}
else if (x.split('.').pop() == 'csv') {
$("#item_type_img").attr("src", "../../Content/images/files_types/csv.png");
}
console.log();
}
function FileConfigHandler()
{
console.log('chal raha h')
var files1 = mfile.files;
console.log(mfile.files);
for (var i = 0; i < files1.length; i++) {
// console.log(files1[i]);
//var x= AddChild(files1[i]);
$('#files').append(x);
}
}
function AddChild(item)
{
var template = $('#files-template').html();
var parent = $(template);
var extention = item.name.split('.').pop();
// console.log(item.name.split('.').pop());
var name = item.name;
var temp_size = item.size;
var size = formatBytes(temp_size);
parent.find('#item_size').text(size)
parent.find('#item_title').text(name)
if (extention == 'pdf') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/pdf.png");
}
else if (extention == 'docx') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/doc.png");
}
else if (extention == 'jpg') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/jpg.png");
}
else if (extention == 'png') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/png.png");
}
else if (extention == 'ppt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/ppt.png");
}
else if (extention == 'txt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/txt.png");
}
else if (extention == 'xls') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/xls.png");
}
else if (extention == 'csv') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/csv.png");
}
return '<li class="uploaded_item">' + parent.html() + '</li>'
}
//function dropHandler(ev) {
// console.log('File(s) dropped');
// // Prevent default behavior (Prevent file from being opened)
// ev.preventDefault();
// var file = ev.dataTransfer.files;
// // var file = e.originalEvent.dataTransfer.files;
// var fileData = new FormData();
// for (var i = 0; i < file.length; i++) {
// fileData.append("fileData", ev.dataTransfer.files[i]);
// }
//if (ev.dataTransfer.items) {
// // Use DataTransferItemList interface to access the file(s)
// for (var i = 0; i < ev.dataTransfer.items.length; i++) {
// // If dropped items aren't files, reject them
// if (ev.dataTransfer.items[i].kind === 'file') {
// file[i] = ev.dataTransfer.items[i].getAsFile();
// fileData.append("fileData",ev.dataTransfer.files[i]);
// console.log('... file[' + i + '].name = ' + file.name);
// }
// }
//} else {
// // Use DataTransfer interface to access the file(s)
// for (var i = 0; i < ev.dataTransfer.files.length; i++) {
// fileData.append("fileData", ev.dataTransfer.files[i]);
// console.log('... file[' + i + '].name = ' + ev.dataTransfer.files[i].name);
// }
//}
// $.ajax({
// type: "POST",
// dataType: "json",
// enctype: 'multipart/form-data',
// url:'/Home/SendFile',
// contentType: false, // Not to set any content header
// processData: false, // Not to process data
// data: fileData,
// success: function (result, status, xhr) {
// alert(result);
// },
// error: function (xhr, status, error) {
// alert(status);
// }
// })
//}
$(document).ready(function () {
$('#uploadFileModal').hide();
$('#drag-and-drop-zone').dmUploader({
onDragEnter: function () {
// Happens when dragging something over the DnD area
this.addClass('active');
$('.upload_container .cloud_upload_img').addClass('animated infinite shake')
},
onDragLeave: function (e) {
// Happens when dragging something OUT of the DnD area
this.removeClass('active');
$('.upload_container .cloud_upload_img').removeClass('animated infinite shake');
//readmultifiles(document.getElementById('#file'));
$('#uploadFileModal').modal("show");
}})
})
$('#mfile').change(function () {
console.log(mfile.files);
$('#uploadFileModal').modal("show");
//document.getElementById("#txt").innerHTML = "1 file has been Selected";
// console.log(mfile.files);
//ChangeImageHandler();
FileConfigHandler();
});
$("#Department").change(function () {
LoadDepartments();
});
function LoadDepartments() {
var collegeId = document.getElementById("Department");
var ID = collegeId.options[collegeId.selectedIndex].value;
var depatments = document.getElementById("CourseId");
console.log(ID);
$.ajax({
url: '#Url.Action("getCourses", "Home")',
type: 'GET',
dataType: "json",
data: { idString: ID },
success: function (result) {
console.log(result)
depatments.innerHTML = "";
$.each(result, function (i, result) {
var options = "<option value='" + result.Id + "' id='" + result.Id + "'>" + result.name + "</option>";
$('#CourseId').append(options);
});
},
failure: function (response) {
alert(response.responseText);
console.log(response.responseText);
},
error: function (response) {
alert(response.responseText);
console.log(response.responseText);
}
});
}
</script>
}
<!-- Debug item template -->
<script type="text/html" id="debug-template">
<li class="list-group-item text-%%color%%"><strong>%%date%%</strong>: %%message%%</li>
</script>
<!-- File item template -->
<script type="text/template" id="files-template">
<li class="uploaded_item">
<div class="item_body">
<div class="item_img_and_info_holder">
<div class="item_type_img_holder">
<img class="item_type_img" id="item_type_img" src="../../Content/images/files_types/pdf.png" />
</div>
<div class="item_info" style="width: 100%">
<h6 class="item_title" id="item_title">%%filename%% </h6>
<div class="item_details" style="margin-bottom: 10px;">
<span class="item_size" id="item_size">00.0 MB</span>
</div>
</div>
</div>
</div>
</li>
</script>
When removing AddChild() from loop it start working
also tried to do shallow copy but it did not work for me
function FileConfigHandler()
{
console.log('chal raha h')
var files1 = mfile.files;
console.log(mfile.files);
for (var i = 0; i < files1.length; i++) {
// console.log(files1[i]);
//var x= AddChild(files1[i]);
$('#files').append(x);
}
}
function AddChild(item)
{
var template = $('#files-template').html();
var parent = $(template);
var extention = item.name.split('.').pop();
// console.log(item.name.split('.').pop());
var name = item.name;
var temp_size = item.size;
var size = formatBytes(temp_size);
parent.find('#item_size').text(size)
parent.find('#item_title').text(name)
if (extention == 'pdf') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/pdf.png");
}
else if (extention == 'docx') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/doc.png");
}
else if (extention == 'jpg') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/jpg.png");
}
else if (extention == 'png') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/png.png");
}
else if (extention == 'ppt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/ppt.png");
}
else if (extention == 'txt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/txt.png");
}
else if (extention == 'xls') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/xls.png");
}
else if (extention == 'csv') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/csv.png");
}
return '<li class="uploaded_item">' + parent.html() + '</li>'
}
I am working on implementing a web chat and have come up with an issue that I hope is easily solvable.
How do I change the color for the sender/receiver to differenciate them?
I have tried to saving the colors into my db but the issue is how I can identify that I am the sender and the receivers color needs to be different.
This is how I have implemented my chat:
Chat.js
connection.on("SessionNotification", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = user + " - " + moment(datetime).format("DD-MM-YYYY HH:mm:ss");
q.textContent = msg;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
});
Html
<script>
$(document).ready(function () {
$('#MessageList').stop().animate({
scrollTop: $('#MessageList')[0].scrollHeight
}, 2000);
var SessionId = document.getElementById("Id").value;
console.log(SessionId);
var form_data = {
"SessionId": SessionId
};
$.ajax({
url: "#Url.Action("GetHistory", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
return false;
});
</script>
<div class="col-sm-12">
<h2>Session</h2>
<hr />
</div>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div id="MessageListContainer">
<ul id="MessageList">
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.CurrentUser)
<input class="form-control col-sm-12" id="Message" type="text" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div class="clearfix">
<div class="pull-right">
<input id="Send" type="button" value="Send" class="btn btn-primary" />
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12">
<hr />
</div>
</div>
<script src="~/aspnet/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
Your AJAX call that comes back as JSON appears to have a few fields like Name and CreatedOn. You can add an additional field server side for the SessionId, which you are injecting server-side anyway into your HTML. Then you can compare to see if the message's session matches yours. If so, then it is you and not the receiver. So you might have something like:
JS
// You set this earlier on
var SessionId = document.getElementById("Id").value;
// ........ OTHER CODE IN BETWEEN
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
// If session ID matches current session (i.e. you) then add different class
if (output[i].SessionId === SessionId) {
// It is you
p.setAttribute("class", "Sender");
} else {
// It is other person
p.setAttribute("class", "Receiver");
}
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
CSS
.Sender {
color: blue;
}
.Receiver {
color: green;
}
I'm having an issue concatenating strings. Where I initially declare the 'output' variable in my last function, I'm able to get the number of questions correct printed to my modal window.
However, my concatenation of strings 2 lines down from that won't work and I've tried so many things. I'm sure it's something simple but any help would be appreciated!
I'm not sure how much code is relevant to the solution so I apologize for the wall of code.
I'm new to JS and my first post on Stackoverflow so any tips or advice is appreciated. Thanks in advance!
var randomNum1 = 0;
var randomNum2 = 0;
var correctAnswer = 0;
var questionNumber = 0;
var question = "<h2>Question #: " + questionNumber + "</h2>";
var answersRight = 0;
//jQuery command to make enter key submit answer
$(document).keypress(function(e) {
if (e.which == 13) {
$("#sub").click();
}
});
//questions object
var questionsAsked = [
];
generateRandom();
document.getElementById('finished').style.display = 'none';
//check answer, push question info to array
function check() {
var userAnswer = parseInt(document.getElementById("userAnswer").value);
document.getElementById('userAnswer').value = "";
if (userAnswer === correctAnswer) {
answersRight++
} else {
answersRight += 0;
}
if (questionNumber < 3) {
next();
} else {
document.getElementById('sub').style.display = 'none';
document.getElementById('submitForm').style.display = 'none';
document.getElementById('finished').style.display = 'block';
finish();
}
}
function random() {
return Math.floor(Math.random() * 50) + 1;
}
//generate random numbers
function generateRandom() {
randomNum1 = random();
randomNum2 = random();
document.getElementById("randomNum1").innerHTML = randomNum1;
document.getElementById("randomNum2").innerHTML = randomNum2;
correctAnswer = randomNum1 + randomNum2;
questionNumber += 1;
question = "<h2>Question #: " + questionNumber + "</h2>";
$("#question").html(question);
questionsAsked.push([questionNumber, randomNum1, randomNum2, correctAnswer]);
}
//next button
function next() {
generateRandom();
}
function finish() {
var output = document.getElementById("quizResults").innerHTML = 'You got ' + answersRight + ' out of ' + questionNumber + ' answers correct!';
var percent = Math.round((answersRight / questionNumber) * 100);
output += ' You got ' + percent + '% on this quiz! Outstanding!';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<div>
<h1 class="text-center">Welcome to Math World!</h1>
</div>
<div>
<div id="question">
</div>
<div id="questionArea">
<br>
<h3>Add the following numbers</h3>
<h3 id="randomNum1"></h3>
<h3>+</h3>
<h3 id="randomNum2"></h3>
<p id="message"></p>
</div>
<div id="submitForm">
<div class="form-inline">
<div class="form-group">
<label for="answer">Enter Answer:</label>
<input type="text" class="form-control" id="userAnswer" placeholder="Type answer here">
</div>
<button id="sub" type="submit" class="btn btn-primary" onclick="check()">Submit Answer</button>
</div>
</div>
<button id="finished" type="submit" class="btn btn-success" data-toggle="modal" data-target="#myModal">Finish Quiz</button>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Quiz Results</h4>
</div>
<div id="quizResults" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script
(Disclaimer: This answer might not actually solve your problem, as noted in the comments. I can't delete it, though, because it was accepted.)
(Please see the other answer)
The line
var output = document.getElementById("quizResults").innerHTML = 'You got '+answersRight+ ' out of ' +questionNumber+ ' answers correct!';
does not have the effect you think it does, because javascript does not interpret a statement like var a = b = c the way you think it does. Instead, it is better to use var a = c; var b = c;, like so:
var output = 'You got '+answersRight+ ' out of ' +questionNumber+ ' answers correct!';
document.getElementById("quizResults").innerHTML = output;
For more information on how javascript interprets var a = b = c;, please see this question: Javascript a=b=c statements
The problem is that you're updating the output variable after you've already put it into the quizResults DIV. Assigning the string to .innerHTML makes a copy of it, it's not a reference to the variable, so updating the variable doesn't change the DIV contents. You need to assign to .innerHTML after you've performed the concatenation.
var randomNum1 = 0;
var randomNum2 = 0;
var correctAnswer = 0;
var questionNumber = 0;
var question = "<h2>Question #: " + questionNumber + "</h2>";
var answersRight = 0;
//jQuery command to make enter key submit answer
$(document).keypress(function(e) {
if (e.which == 13) {
$("#sub").click();
}
});
//questions object
var questionsAsked = [
];
generateRandom();
document.getElementById('finished').style.display = 'none';
//check answer, push question info to array
function check() {
var userAnswer = parseInt(document.getElementById("userAnswer").value);
document.getElementById('userAnswer').value = "";
if (userAnswer === correctAnswer) {
answersRight++
} else {
answersRight += 0;
}
if (questionNumber < 3) {
next();
} else {
document.getElementById('sub').style.display = 'none';
document.getElementById('submitForm').style.display = 'none';
document.getElementById('finished').style.display = 'block';
finish();
}
}
function random() {
return Math.floor(Math.random() * 50) + 1;
}
//generate random numbers
function generateRandom() {
randomNum1 = random();
randomNum2 = random();
document.getElementById("randomNum1").innerHTML = randomNum1;
document.getElementById("randomNum2").innerHTML = randomNum2;
correctAnswer = randomNum1 + randomNum2;
questionNumber += 1;
question = "<h2>Question #: " + questionNumber + "</h2>";
$("#question").html(question);
questionsAsked.push([questionNumber, randomNum1, randomNum2, correctAnswer]);
}
//next button
function next() {
generateRandom();
}
function finish() {
var output = 'You got ' + answersRight + ' out of ' + questionNumber + ' answers correct!';
var percent = Math.round((answersRight / questionNumber) * 100);
output += ' You got ' + percent + '% on this quiz! Outstanding!';
document.getElementById("quizResults").innerHTML = output;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<div>
<h1 class="text-center">Welcome to Math World!</h1>
</div>
<div>
<div id="question">
</div>
<div id="questionArea">
<br>
<h3>Add the following numbers</h3>
<h3 id="randomNum1"></h3>
<h3>+</h3>
<h3 id="randomNum2"></h3>
<p id="message"></p>
</div>
<div id="submitForm">
<div class="form-inline">
<div class="form-group">
<label for="answer">Enter Answer:</label>
<input type="text" class="form-control" id="userAnswer" placeholder="Type answer here">
</div>
<button id="sub" type="submit" class="btn btn-primary" onclick="check()">Submit Answer</button>
</div>
</div>
<button id="finished" type="submit" class="btn btn-success" data-toggle="modal" data-target="#myModal">Finish Quiz</button>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Quiz Results</h4>
</div>
<div id="quizResults" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script