Simple quiz - how to get clicked values and send it to php - javascript

I have to write a simple quiz app. As I picked it after someone this is what I have.
There are 10 questions with 3 answers each. All question are loaded at once and only one visible. After clicking the answer next question shows up etc.
However as javascript is kinda magic to me I have no clue how to get all answers and send it to php to check if user chose correct.
The code looks something like this:
<form action="result.php">
<div class=“quiz>
<div class=“question”> Some question ?
<ul>
<li><a href=“#”>Answer A</a></li>
<li><a href=“#”>Answer B</a></li>
<li><a href=“#”>Answer C</a></li>
</ul>
</div>
[… more question here …]
<div class="question">Last question ?
<ul>
<li>Answer A</li>
<li>Answer B</li>
<li>Answer C</li>
</ul>
</div>
</div>
<input type=“hidden” name=“answers” value=“answers[]>
</form>
So basically user click on answer, next question pop up and at the end I need to populate all answer and send it to result.php where somehow I would get results within array with chosen answers like {1,3,2,1,2,3,1,2,3,1} or something like that.

There are many ways to accomplish this. Here's an easy one:
add a
<input type="hidden" name="questions[]" value="" />
inside each .question DIV
update the value of this input when one of the links are clicked:
$('.question a').on('click', function(){
var answer = $(this).text();
$(this).parents('.question').find('input').val(answer);
});
put a request method on your form, let's say POST
Then in your PHP script you'll get a numerically indexed array with the selected answer for each question, $_POST['questions'].
I do not know how your design looks like, but it may be possible to achieve this without any javascript, using hidden radio inputs and labels (I'm assuming here you're using links because of styling limitations on input fields).

Normally, you would create an HTTP request to your verification back-end. jQuery, for one, makes this quite easy. Also, I would try to generate the questions HTML, so that you're ready to generate quizzes with other sets of questions without having to re-type your html.
I'm trying to create a quizz-like app myself, currently, and would be glad to hear your feedback. A brief snipped of what I mean is on this fiddle: http://jsfiddle.net/xtofl/2SMPd/
Basically something like:
function verify(answers) {
jQuery.ajax("http://yoursite/verify.php?answers="+answers,
{ async: true,
complete: function(response, status){
// e.g.
alert(response.text);
}
};
};
This request would be sent when all answers are completed. I would try to create the questions on-the-fly using javascript and the DOM, something like:
function retrieveQuestions() {
//TODO: get them from a json-request like http://yourquizz/quizz1/questions
return [{ text: "what if Zoo went to Blohom in a Flurk?",
options: { a: "he frunts and vloghses",
b: "the Blohom doesn't snorf anymore" }
},
{ text: "how many this and that",
options: { a: "1", b: "2", c: "14" }
}
];
};
// retrieve and create the questions elements
var questions = retrieveQuestions();
questions.forEach(function(question, index){
jQuery("#questions").append(createQuestionElement(question));
});
// what does a question element look like:
function createQuestionElement(question){
var li=document.createElement("li");
var options = [];
Object.keys(question.options).forEach(function(key){
var o = document.createElement("div");
jQuery(o).on('click', function(){question.answer=jQuery(o).val();});
li.appendChild(o);
});
return li;
}
Your php backend verify.php script will check the arguments and return the result in json format, e.g.:
$correct = ($answers[ $_GET["question"] ] == $_GET["answer"]);
print("{ 'correct': '$correct' }");
(provided your answers are stored in an array $answers.

Yet another solution to the problem:
jsFiddle
We use event handlers, to check if an answer was clicked, then add the index of the answer to an array. When the last answer was submitted, we send the data to a php page, where you can process it using the $_POST array.
$('.question a').on('click', function (e) {
e.preventDefault();
var self = $(this);
var ans = self.parent().index() + 1;
answers.push(ans);
var hasNext = nextQuestion();
if (!hasNext) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"answers": answers
}
}).done(function (response) {
response = 'Stuff you output with PHP';
$('body').append('<p> Result: ' + response + '</p>');
});
}
});

Related

AngularJS - Get printed value from scope inside an attribute?

I'm currently working on an AngularJS project and I got stuck in this specific requirement.
We have a service that has all the data, DataFactoryService. Then, I have a controller called DataFactoryController that is making the magic and then plot it in the view.
<div ng-repeat = "list in collection">
{{list.name}}
...
</div>
Now, we have a requirement that pass multiple data into one element. I thought an "ng-repeat" would do, but we need to have it inside an element attribute.
The scenarios are:
At one of the pages, we have multiple lists with multiple data.
Each data has a unique code or ID that should be passed when we do an execution or button click.
There are instances that we're passing multiple data.
Something like this (if we have 3 items in a list or lists, so we're passing the 3 item codes of the list):
<a href = "#" class = "btn btn-primary" data-factory = "code1;code2;code3;">
Submit
</a>
<a href = "#" class = "btn btn-default" data-factory = "code1;code2;code3;">
Cancel
</a>
In the example above, code1,code2,code3 came from the list data. I tried several approach like "ng-repeat", "angular.each", array, "ng-model" but I got no success.
From all I've tried, I knew that "ng-model" is the most possible way to resolve my problem but I didn't know where to start. the code below didn't work though.
<span ng-model = "dataFactorySet.code">{{list.code}}</span>
{{dataFactorySet.code}}
The data is coming from the service, then being called in the controller, and being plot on the HTML page.
// Controller
$scope.list = dataFactoryService.getAllServices();
The data on the list are being loaded upon initialization and hoping to have the data tags initialized as well together with the list data.
The unique code(s) is/are part of the $scope.list.
// Sample JSON structure
[
{ // list level
name: 'My Docs',
debug: false,
contents: [ // list contents level
{
code: 'AHDV3128',
text: 'Directory of documents',
...
},
{
code: 'AHDV3155',
text: 'Directory of pictures',
...
},
],
....
},
{ // list level
name: 'My Features',
debug: false,
contents: [ // list contents level
{
code: 'AHGE5161',
text: 'Directory of documents',
...
},
{
code: 'AHGE1727',
text: 'Directory of pictures',
...
},
],
....
}
]
How can I do this?
PLUNKER -> http://plnkr.co/edit/Hb6bNi7hHbcFa9RtoaMU?p=preview
The solution for this particular problem could be writing 2 functions which will return the baseId and code with respect to the list in loop.
I would suggest to do it like below
Submit
Cancel
//inside your controller write the methods -
$scope.getDataFactory = function(list){
var factory = list.map( (a) => a.code );
factory = factory.join(";");
return factory;
}
$scope.getDataBase= function(list){
var base= list.map( (a) => a.baseId);
base= base.join(";");
return base;
}
Let me know if you see any issue in doing this. This will definitely solve your problem.
You don't really have to pass multiple data from UI if you are using Angular.
Two-way data binding is like blessing which is provided by Angular.
check your updated plunker here [http://plnkr.co/edit/mTzAIiMmiVzQfSkHGgoU?p=preview]1
What I have done here :
I assumed that there must be some unique id (I added Id in the list) in the list.
Pass that Id on click (ng-click) of Submit button.
You already have list in your controller and got the Id which item has been clicked, so you can easily fetch all the data of that Id from the list.
Hope this will help you... cheers.
So basing from Ashvin777's post. I came up with this solution in the Controller.
$scope.getFactoryData = function(list) {
var listData = list.contents;
listData = listData.map(function(i,j) {
return i.code;
});
return listData.join(';');
}

How to use javascript to change content value?

I am currently developing a system which user can only view the name with the start character.
Below is the example :
When I click on the "A" link, the below table will show the name which start from "A" and will not shows the rest of the records.
I am trying to use href to pass operation to my php but it is not flexible to do so. Therefore, I looking for javascript to help me go through this. What I want to do is the page will not refresh and will direct change the content when I click on the A~Z link.
This is my HTML code :
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
This is my php page which execute data from table :
$rsa = array();
$sqladded = false;
$appliedfilter = array();
if($_REQUEST['op'] = ''){
$record = 'A';
}
else{
$record = $_REQUEST['op'];
}
$stmt = $getuser->getuser($record);
if ($rs = $db->Execute($stmt))
{
$arrResult = array();
while($rsa = $rs->FetchRow())
{
array_push($arrResult, array(
"name" => $rsa['name'],
"mobile_no" => $rsa['mobile_no'],
"email" => $rsa['email'],
"address" => $rsa['address'],
"current_professional" => $rsa['current_professional'],
"others" => $rsa['others']
));
}
$tpl->display("alumni-listing.html");
}
And this is my SQL statement :
function getuser($record)
{
global $db;
$arrResult = array();
$stmt = "SELECT * FROM "._CONST_TBL_ALUMNI." WHERE name LIKE ".$record."%";
if($rs = $db->Execute($stmt))
{
$arrResult = $rs->GetArray();
}
return $arrResult;
}
Hope someone can help me.
Thanks in advanced.
Anyhow you have to use the calls to the PHP page.
If not then you can make a the 1st call load all data (A-Z) and then display the connects with just a click. But then your 1st call would be big and it will take time to load if data is greater.
You can use Ajax calls.
Structure your HTML as this way.
<li><a href="#" class='ajaxCaller>A</a></li>
<li><a href="#" class='ajaxCaller>B</a></li>
<li><a href="#" class='ajaxCaller>C</a></li>
<li><a href="#" class='ajaxCaller>D</a></li>
<li><a href="#" class='ajaxCaller>E</a></li>
<li><a href="#" class='ajaxCaller>F</a></li>
The Ajax calls should be
$('a.ajaxCaller').click(function(event){
event.preventDefault();
var x=$(this).text();
$.ajax({
url: "alumni-listing.php",
data: {op:x}
}).done(function() {
// You can have your code to set the returned page, to the specific div.
});
});
I have made lots of project like the one you ask. Learning to use jQuery a javascript framework would be the best solution to solve the task. jQuery made ajax process very simple using jQuery.post().
So the way I see it, your problem boils down to dynamically querying the database on a Dom-event (i.e, through javascript) and not navigating to a different page. Which is lucky, because AJAX was developed pretty much for this - smaller 'refreshes'.
Use JS to trigger a php request, and parse the return
Check out jQuery's Post. I am sure it can be accomplished without, so please edit the question if jQuery is a no-no. If you change your php page to just echo a JSON of the result, and call if from JS, you can parse the JSON and display it in the html page.
HTML
<li><a class="listing-filter" href="alumni-listing.php?op=a">A</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=b">B</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=c">C</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=d">D</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=e">E</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=f">F</a></li>
Javascript
$('.listing-filter').click(function (e) {
var $filter = $(e.currenttarget),
filterValue = $filter.html();
RefreshPageWithData(filterValue);
});
function RefreshPageWithData( filterBy ) {
var data = {
op: filterBy,
};
$.post(pathname-on-server.php, data, function (response) {
//Parse the response
var results = JSON.parse(response);
//Construct the DOM
var newHtml;
//Append it to existing element
$('#container').html(newHtml);
});
Please note that anything you echo in the php page is the response passed back to the JS callback. So, a simple idea might be to echo json_encode($arrResult). I suggest having one index.php that serves the file as you do above, and another that does similar tasks but echoes the retrieved data. This avoids a double-server request for the homepage.

Having issues tying together basic javascript chat page

I have the skeleton of a chat page but am having issues tying it all together. What I'm trying to do is have messages sent to the server whenever the user clicks send, and also, for the messages shown to update every 3 seconds. Any insights, tips, or general comments would be much appreciated.
Issues right now:
When I fetch, I append the <ul class="messages"></ul> but don't want to reappend messages I've already fetched.
Make sure my chatSend is working correctly but if I run chatSend, then chatFetch, I don't retrieve the message I sent.
var input1 = document.getElementById('input1'), sendbutton = document.getElementById('sendbutton');
function IsEmpty(){
if (input1.value){
sendbutton.removeAttribute('disabled');
} else {
sendbutton.setAttribute('disabled', '');
}
}
input1.onkeyup = IsEmpty;
function chatFetch(){
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
method: "GET",
success: function(data){
$(".messages").clear();
for(var key in data) {
for(var i in data[key]){
console.log(data[key][i])
$(".messages").append("<li>"+data[key][i].text+"</li>");
}
}
}
})
}
function chatSend(){
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input1.draft').val()}),
success:function(message){
}
})
}
chatFetch();
$("#sendbutton").on('click',chatSend());
This seems like a pretty good project for Knockout.js, especially if you want to make sure you're not re-appending messages you've already sent. Since the library was meant in no small part for that sort of thing, I think it would make sense to leverage it to its full potential. So let's say that your API already takes care of limiting how many messages have come back, searching for the right messages, etc., and focus strictly on the UI. We can start with our Javascript view model of a chat message...
function IM(msg) {
var self = this;
self.username = ko.observable();
self.message = ko.observable();
self.timestamp = ko.observable();
}
This is taking a few liberties and assuming that you get back an IM object which has the name of the user sending the message, and the content, as well as a timestamp for the message. Probably not too far fetched to hope you have access to these data elements, right? Moving on to the large view model encapsulating your IMs...
function vm() {
var self = this;
self.messages = ko.observableArray([]);
self.message = ko.observable(new IM());
self.setup = function () {
self.chatFetch();
self.message().username([user current username] || '');
};
self.chatFetch = function () {
$.getJSON("https://api.parse.com/1/classes/chats", function(results){
for(var key in data) {
// parse your incoming data to get whatever elements you
// can matching the IM view model here then assign it as
// per these examples as closely as possible
var im = new IM();
im.username(data[key][i].username || '');
im.message(data[key][i].message || '');
im.timestamp(data[key][i].message || '');
// the ([JSON data] || '') defaults the property to an
// empty strings so it fails gracefully when no data is
// available to assign to it
self.messages.push(im);
}
});
};
}
All right, so we have out Javascript models which will update the screen via bindings (more on that in a bit) and we're getting and populating data. But how do we update and send IMs? Well, remember that self.message object? We get to use it now.
function vm() {
// ... our setup and initial get code
self.chatSend = function () {
var data = {
'user': self.message().username(),
'text': self.message().message(),
'time': new Date()
};
$.post("https://api.parse.com/1/classes/chats", data, function(result) {
// do whatever you want with the results, if anything
});
// now we update our current messages and load new ones
self.chatFetch();
};
}
All right, so how do we keep track of all of this? Through the magic of bindings. Well, it's not magic, it's pretty intense Javascript inside Knockout.js that listens for changes and the updates the elements accordingly, but you don't have to worry about that. You can just worry about your HTML which should look like this...
<div id="chat">
<ul data-bind="foreach: messages">
<li>
<span data-bind="text: username"></span> :
<span data-bind="text: message"></span> [
<span data-bind="text: timestamp"></span> ]
</li>
</ul>
</div>
<div id="chatInput">
<input data-bind="value: message" type="text" placeholder="message..." />
<button data-bind="click: $root.chatSend()">Send</button>
<div>
Now for the final step to populate your bindings and keep them updated, is to call your view model and its methods...
$(document).ready(function () {
var imVM = new vm();
// perform your initial search and setup
imVM.setup();
// apply the bindings and hook it all together
ko.applyBindings(imVM.messages, $('#chat')[0]);
ko.applyBindings(imVM.message, $('#chatInput')[0]);
// and now update the form every three seconds
setInterval(function() { imVM.chatFetch(); }, 3000);
});
So this should give you a pretty decent start on a chat system in an HTML page. I'll leave the validation, styling, and prettifying as an exercise to the programmer...

creating a dynamic form that builds a multi dimensional array

I am a php developer that is new to angular and javascript in general but finding it really powerful and fast for creating interactive UIs
I want to create a form for a user to create an object called a program, a program has some basic info like title and description and it can have many weeks. I want their to be an 'add week' button that when pressed displays a group of form fields related to weeks, if pushed again it shows another group of form fields to fill in the second weeks information.
edit1: specifically, how I am adding the objects to scope.program with the addWeeks method.
secondly when I console.log the $scope.program it just looks very messy a lot of arrays within objects within objects. it just dosnt look like a clean array of data but maybe thats just because I am not used to javascript and or json? Each week is going to have up to 7 days obviously and each day can have numerous events so it just seems to me like it is going to be quite messy but maybe I should just have faith :p
finally how the addProgram method is creating the json object to be sent to the server
when the form is submitted it should post a json object that looks something like this
program {
title: 'name of programme',
desc: 'description of programme',
weeks: [
{
item1: 'foo',
item2: 'more foo'
},
{
item1: 'foo2',
item2: 'more foo 2'
}
]
]
}
here is a codepen of what I am doing right now but I am not sure it is the best or even an ok way to do it, particularly how I am appending the arrays/objects in teh addWeek method.
there are going to be many more layers to the form and the object it is posting(days, sessions, excersises etc) so I want to get the basics of doing this right before adding all of that.
html
<div ng-app="trainercompare">
<div ng-controller="programsController">
<input type="text" placeholder="Program Title" ng-model="program.title"></br>
<input type="text" placeholder="Program Focus" ng-model="program.focus"></br>
<input type="text" placeholder="Program Description" ng-model="program.desc"></br>
<button ng-click="addWeek()"> add week</button>
<div ng-repeat="week in program.weeks">
<input type="text" placeholder="Name the week" ng-model="week.name">
<input type="text" placeholder="Describe It" ng-model="week.desc">
{{ week.name }}</br>
{{ week.desc }}</br>
</div>
<button ng-click="addProgram()"> add program</button>
</div>
</div>
app.js
var myModule = angular.module("trainercompare", ['ui.bootstrap']);
function programsController($scope, $http) {
$scope.program = {
weeks: [{
}]
};
$scope.addWeek = function() {
$scope.program.weeks.push(
{
}
);
};
function isDefined(x) {
var undefined;
return x !== undefined;
}
$scope.addProgram = function() {
var program = {
title: $scope.program.title,
focus: $scope.program.focus,
desc: $scope.program.desc,
weeks: []
};
angular.forEach($scope.program.weeks, function(week, index){
var weekinfo = {
name: week.name,
desc: week.desc
};
program.weeks.push(weekinfo);
});
$http.post('/programs', program).success(function(data, status) {
if(isDefined(data.errors)) {
console.log(data.errors);
}
if(isDefined(data.success)) {
console.log(data.success);
}
});
};
}
Looks to me like you've got a good grasp on it. The addWeek code looks correct. The extra data you see when you console.log your model is some of Angular's internal stuff to track bindings. When you post that to your server it should be cleaned up by Angular.
Angular has a JSON function that removes all of the hash values and other 'angular' things from your JSON. That's why they start with a $ so it knows to remove them.
This happens automatically when you use $http, it's in the documentation here:
If the data property of the request configuration object contains an object, serialize it into JSON format.
Since Angular will clean up the hashes and things, you don't need to "rebuild" the model when you're posting it... just set data to $scope.program and remove 70% of the code in $scope.addProgram.
To learn more specifically how Angular cleans up the JSON, look at this answer: Quick Way to "Un-Angularize" a JS Object

How to go trough JavaScript array?

I have this output from ajax call:
"total":"3",
"data":[{ "id":"4242",
"title":"Yeah Lets Go!",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah"
}]
So there is three that kind of items in that array and I would need to go that through and print actual html out of it. So on page it would be:
Yeah Lets Go! (which is a link to http:www.domain.com/yeah)
Created: 2010-07-24 13:19:24
I'm clueles with this one.
Edit 1:
Also atm I get that raw output after clicking link. How can I get it to show on page load? Or it does that ajax call when I click link atm.
Edit 2:
I got it to output everything at once. But still I have a prolem with putting it actual html. The output atm is:
"total":"3",
"data":[{
"id":"4242",
"title":"Yeah Lets Go!",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah"
}
{
"id":"4242",
"title":"Yeah Lets Go!222",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah222"
}
{
"id":"4242",
"title":"Yeah Lets Go!333",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah333"
}
]}
I would like to get that into list with title and link and creation day.
Edit 3 after answer from Luca Matteis:
Hmm, now im even more confused.
That JSON string comes out of this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true',
null,
function(data, status, xhr) {
$('#contentCell').html(data);
}
);
So I would need to do for that is something like:
var html = eval(data);
and then I would do what Luca Matteis suggest?
First off, that's a JSON string, you need to un-serialize the string into a real JavaScript object (look at json.org for this).
Once you have the native JavaScript data, something like this should work:
var html = '';
for(var i=0; i < obj.data.length; i++) {
html += ''+obj.data[i].title+'<br>';
html += 'Created: '+ obj.data[i].created;
}
Hmm, now im even more confused.
That JSON string comes out of this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', null, function(data, status, xhr) {
$('#contentCell').html(data);
});
So I would need to do for that is something like:
var html = eval(data);
and then I would do what Luca Matteis suggest?

Categories