Button calls entirely different function than what its supposed to - javascript

What i want to happen is when i click the button after typing yes, it says "OLD MAN: thats good to hear, whats your name?" but instead it calls a different function saying the else answer for the question that has not been added yet. This is probably me being very dumb, because im new and bad at html/jss but if anyone sees why this is happening and let me know it would be greatly apreciated
the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet"type="text/css"/>
<script src="script.js"></script>
</head>
<body onload="onload()">
<center>
<h1 class="Title"> Text Adventure HMTL </h1>
<h5> Please write your answer directly how it was written after the question</h5>
<br><br>
</center>
<p id="currentQuestion">
<p id="givenAnswers"></p>
<input type="textbox" id="answer" placeholder="Type your answer here">
<input id="enter" type="button" onclick="wakeUp()" value="enter">
</body>
</html>
the js:
var answers="Yes<br>No"
var name=""
function onload(){
document.getElementById("currentQuestion") .innerHTML=currentQuestion=currentQuestion
document.getElementById("givenAnswers").innerHTML=answers
}
function wakeUp(){
document.getElementById("currentQuestion").innerHTML=currentQuestion
document.getElementById("givenAnswers").innerHTML=answers
if(document.getElementById("answer").value=="No" || document.getElementById("answer").value=="no" )
{
currentQuestion="You did not wake up, the game has ended, please restart"
answers=""
document.getElementById("answer").value=""
onload()
document.getElementById("enter").onlclick = "dead()"
}
else if(document.getElementById("answer").value=="Yes" || "yes" ){
currentQuestion="OLD MAN: Good morning, how are you feeling?"
answers="Good<br>Bad<br>Else"
document.getElementById("answer").value=""
document.getElementById("enter").onlclick = howUFeel()
}
else{
document.getElementById("answer").value=""
}
}
function dead(){
currentQuestion="You have died, please restart"
document.getElementById("currentQuestion").innerHTML=currentQuestion
document.getElementById("answer").value=""
onload()
}
function howUFeel(){
if (document.getElementById("answer").value == "else" || "Else" )
{
currentQuestion="What do you mean by else? care to elaborate?"
answers="No"
onload()
document.getElementById("answer").value=""
}
else if(document.getElementById("answer").value == "good" || "Good" ){
currentQuestion="OLD MAN: Im Happy to hear it, do you by chance remember your name?"
}
else{
}
}
Here you can test it and see what it does: https://idkwthisgoingon.kitten3604.repl.co/

Edited Answer
You are using if incorrectly: if(something == option1 || option2) doesn't work like you think it does.
do:
if(document.getElementById('answer').value == option1 || document.getElementById('answer').value == option2)
in your checks.
if(something == string1 || string2) will always return true because a non-empty string is always considered true when converting into a boolean therefore the second condition in the if statement, which is string2, will be true
EDIT
While I already answered the question, I would like to give you a piece of advice:
Try to generalize your code as much as you can. it will make your code shorter and more readable, and it will also become helpful when adding functionality and complexity to the code.
Here is my implementation of the dialog mechanic which tries to follow this advice:
/* the dialog is represented by a nested object of the following form:
const dialogTree = {
'output': 'First Question',
'options': {
'option1': {
'output': 'new question',
'onselect': '\\<function to be executed when answering with this option\\>',
'options': {
'option1.1': {'output': 'new question', 'onselect': '...', 'options': {'...': '...'}},
'option1.2': {'output': 'new question', 'onselect': '...', 'options': {'...': '...'}},
}
},
'option2': {
'output': 'new question',
'onselect': '<function to be executed when answering with this option, leave empty for no special effects>',
'options': {
'option2.1': {'output': 'new question', 'onselect': '...', 'options': {'...': '...'}},
'option2.2': {'output': 'new question', 'onselect': '...', 'options': {'...': '...'}},
}
},
}
};
*/
// notes:
// - onselect is for special effects so don't include it if you don't want anything to happen (outside of the dialog continuing of course)
// - don't use special characters in the 'output' value (for instance <,>), instead use their entity number (see example)
// example for a dialog tree:
const dialogTree = {
'output': 'How are you feeling today?',
'options': {
'Good': {
'output': 'That\'s great, do you have anything to say to me?',
'options': {
'Not really': {'onselect': die},
'Yes, but it\'s a secret, so come close': {
'output': 'Ok, I\'m close, what is it?',
'options': {'&#60I can\'t think of a funny thing to write here&#62': {'onselect': die}}}
}
},
'Bad': {
'output': 'Why?',
'options': {
'Because this code looks bad': {
'output': 'That\'s hurtful :(',
'options': {
'*truthful': {'onselect': die}
}
},
'Because I don\'t like you': {
'onselect': die
},
}
},
'I don\'t want to talk': {
'onselect': die,
}
}
};
let prefix = 'Old Man: '; // prefix to go before each message
let dialogPath = []; // stores array of the answers so far
// some elements:
let questionEl = document.getElementById('current-question');
let givenAnswersEl = document.getElementById('given-answers');
let dialogDivEl = document.getElementById('dialog');
let deathMsgEl = document.getElementById('death-message');
// the current dialog tree (object):
let currentDialogTree = Object.create(dialogTree);
// function to be called to update the html to match the dialog data:
function flush() {
// setting current question:
questionEl.innerHTML = prefix + currentDialogTree.output;
// clearing the given answers:
givenAnswersEl.innerHTML = '';
let id = 0;
// adding given answers one by one.
for(let option in currentDialogTree.options) {
let newOption = document.createElement('input');
newOption.type = 'radio';
newOption.name = 'option';
newOption.value = option;
newOption.id = `option-${id}`;
givenAnswersEl.appendChild(newOption); // adding the option to the div
let newLabel = document.createElement('label');
newLabel.innerHTML = option;
newLabel.for = `option-${id}`;
givenAnswersEl.appendChild(newLabel); // adding the label to the div
givenAnswersEl.appendChild(document.createElement('br')); // adding a break to the div
id ++;
}
}
flush();
function getAnswer() {
let options = givenAnswersEl.children;
// for each of the given answers check if it is checked, and if so return it:
for(let option of options) {
if(option.checked) {
return option.value;
}
}
// if none found, return false:
return false;
}
// function to be called when user submits an answer:
function submit() {
let answer = getAnswer();
// check if an answer was given:
if(!answer) { return; }
// update dialog:
dialogPath.push(answer);
currentDialogTree = currentDialogTree.options[answer];
if(currentDialogTree.onselect) {
if(currentDialogTree.onselect()) {
// if an onselect function has a return value then we assume that it is die(), so we return:
return;
};
}
flush();
}
// function to be called when recalculating the current dialog tree:
function updateCurrentTree() {
// reset dialog tree:
currentDialogTree = Object.create(dialogTree);
// for each option in the dialogPath, narrow the dialogTree as if that option was chosen
for(let option of dialogPath) {
currentDialogTree = currentDialogTree.options[option];
}
}
function die() {
// hide dialog div:
dialogDivEl.style.display = 'none';
// show respawn div:
deathMsgEl.style.display = 'initial';
return true;
}
// function to be called to reset the dialog:
function reset() {
// hide respawn div:
deathMsgEl.style.display = 'none';
// show dialog div:
dialogDivEl.style.display = 'initial';
dialogPath.length = 0; // clearing the dialog path
updateCurrentTree(); // updating currnet dialog tree
flush();
}
// function for going back one step in the dialog:
function backstep() {
if(dialogPath.length) {
dialogPath.pop();
updateCurrentTree();
flush();
}
}
body {
font-family: cursive;
}
#given-answers {
margin-top: 10px;
margin-bottom: 10px;
}
button {
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="dialog">
<p id="current-question"></p>
<div id="given-answers">
</div>
<button id="enter" onclick="submit()">enter</button>
<button id="backstep" onclick="backstep()">undo</button>
</div>
<div id="death-message" style="display: none;">
<p>You died! click the button to restart</p>
<button id="restart" onclick="reset()">restart</button>
</div>
</body>
</html>

Related

change text after time using jQuery?

There are already some answers on this site but couldn't figure out what I need.
Using the answer accepted as good given here: How can I change text after time using jQuery?
But, instead of having an alert, I'd like to make it reload to its first message (adding full codes for clarity:
function nextMsg() {
if (messages.length == 0) {
// once there is no more message, I don't know how to start the script over (loop it)
} else {
$('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}
};
var messages = [
"Hello!",
"This is a website!",
"You are now going to be redirected.",
"Are you ready?",
"You're now being redirected..."
].reverse();
$('#message').hide();
nextMsg();
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>
On another answer I had also find something similar, but I couldn't add fade in and fade out:
var example = [' link1', ' link2'];
textSequence(0);
function textSequence(i) {
if (example.length > i) {
setTimeout(function() {
document.getElementById("sequence").innerHTML = example[i];
textSequence(++i);
}, 5000); // milliseconds
} else if (example.length == i) { // Loop
textSequence(0);
}
}
<div id="sequence"></div>
This may seem like a simple answer, but while I understand html and css to an extent, jscript is still out of my reach, so an answer with some clarity onto it would be great.
Thanks to anyone that will answer.
Using pop in the first example is actively removing elements from your messages array - so you can't "start the script over" because you have basically destroyed your data.
Think of pop as taking an items out of a bag one at a time and throwing them away - obviously when there are no items left in the bag - you can't then start again trying to get items out of the bag - because there is nothing left in the bag.
function nextMsg(index) {
if (messages.length === index) {
nextMsg(0);
} else {
$('#message').html(messages[index])
.fadeIn(500)
.delay(1000)
.fadeOut(500, () => nextMsg(index + 1));
}
};
var messages = [
' link1',
' link2',
' link3',
' link4'
];
$('#message').hide();
nextMsg(0);
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
As you can see there is no need to copy or duplicate the data - nor is there any need to reverse the messages.
Simply use the message index to keep track of which message to display and loop the index.
You are using pop to empty the original list. You need to keep the original list in place in order to start over:
function nextMsg() {
if (messages.length == 0) {
messages = copy(originalMessages);
nextMsg();
} else {
$('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}
};
var originalMessages = [
"Hello!",
"This is a website!",
"You are now going to be redirected.",
"Are you ready?",
"You're now being redirected..."
].reverse()
var messages = copy(originalMessages);
function copy(x){
return JSON.parse(JSON.stringify(x));
}
$('#message').hide();
nextMsg();
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>
Try it :
var example = [' link1', ' link2'];
textSequence(0);
function textSequence(i) {
$('#sequence').html(example[i])
$('#sequence').fadeIn(500)
if (example.length > i) {
setTimeout(function() {
$('#sequence').fadeOut(500);
setTimeout(function() {
textSequence(++i);
},600);
}, 5000);
} else if (example.length == i) { // Loop
textSequence(0);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id='sequence'></div>

I have to double click a button in order for a function to work in js

I'm trying to implement a simple speech to text and then text to speech as a response to the initial speech to text input!
I'm using code from another open source site for both the speech synthesis and text 2 speech, so I don't fully understand the code.
Basically, what is happening is that when I am finished speaking the input, I press the pause-record-btn which is supposed to trigger myFunction(), yet I have to press the button twice!
(I am VERY new to js but do understand a bit of front end development (css, html) so any help will be very appreciated )
Code Pen
/*-----------------------------
Voice Recognition Script
------------------------------*/
try {
var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
var recognition = new SpeechRecognition();
}
catch(e) {
console.error(e);
$('.no-browser-support').show();
$('.app').hide();
}
var noteTextarea = $('#note-textarea');
var instructions = $('#recording-instructions');
var notesList = $('ul#notes');
var noteContent = '';
// Get all notes from previous sessions and display them.
var notes = getAllNotes();
renderNotes(notes);
/*-----------------------------
Voice Recognition
------------------------------*/
// If false, the recording will stop after a few seconds of silence.
// When true, the silence period is longer (about 15 seconds),
// allowing us to keep recording even when the user pauses.
recognition.continuous = true;
// This block is called every time the Speech APi captures a line.
recognition.onresult = function(event) {
// event is a SpeechRecognitionEvent object.
// It holds all the lines we have captured so far.
// We only need the current one.
var current = event.resultIndex;
// Get a transcript of what was said.
var transcript = event.results[current][0].transcript;
// Add the current transcript to the contents of our Note.
// There is a weird bug on mobile, where everything is repeated twice.
// There is no official solution so far so we have to handle an edge case.
var mobileRepeatBug = (current == 1 && transcript == event.results[0][0].transcript);
if(!mobileRepeatBug) {
noteContent += transcript;
noteTextarea.val(noteContent);
}
};
recognition.onstart = function() {
instructions.text('Voice recognition activated. Try speaking into the microphone.');
}
recognition.onspeechend = function() {
instructions.text('You were quiet for a while so voice recognition turned itself off.');
}
recognition.onerror = function(event) {
if(event.error == 'no-speech') {
instructions.text('No speech was detected. Try again.');
};
}
/*-----------------------------
App buttons and input
------------------------------*/
$('#start-record-btn').on('click', function(e) {
if (noteContent.length) {
noteContent += ' ';
}
recognition.start();
});
$('#pause-record-btn').on('click', function(e) {
recognition.stop();
instructions.text('Voice recognition paused.');
});
// Sync the text inside the text area with the noteContent variable.
noteTextarea.on('input', function() {
noteContent = $(this).val();
})
$('#save-note-btn').on('click', function(e) {
recognition.stop();
if(!noteContent.length) {
instructions.text('Could not save empty note. Please add a message to your note.');
}
else {
// Save note to localStorage.
// The key is the dateTime with seconds, the value is the content of the note.
saveNote(new Date().toLocaleString(), noteContent);
// Reset variables and update UI.
noteContent = '';
renderNotes(getAllNotes());
noteTextarea.val('');
instructions.text('Note saved successfully.');
}
})
notesList.on('click', function(e) {
e.preventDefault();
var target = $(e.target);
// Listen to the selected note.
if(target.hasClass('listen-note')) {
var content = target.closest('.note').find('.content').text();
readOutLoud(content);
}
// Delete note.
if(target.hasClass('delete-note')) {
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
}
});
/*-----------------------------
Speech Synthesis
------------------------------*/
function readOutLoud(message) {
var speech = new SpeechSynthesisUtterance();
// Set the text and voice attributes.
speech.text = message;
speech.volume = 1;
speech.rate = 1;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
}
/*-----------------------------
Helper Functions
------------------------------*/
function renderNotes(notes) {
var html = '';
if(notes.length) {
notes.forEach(function(note) {
html+= `<li class="note">
<p class="header">
<span class="date">${note.date}</span>
Listen to Note
Delete
</p>
<p class="content">${note.content}</p>
</li>`;
});
}
else {
html = '<li><p class="content">You don\'t have any notes yet.</p></li>';
}
notesList.html(html);
}
function saveNote(dateTime, content) {
localStorage.setItem('note-' + dateTime, content);
}
function getAllNotes() {
var notes = [];
var key;
for (var i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
if(key.substring(0,5) == 'note-') {
notes.push({
date: key.replace('note-',''),
content: localStorage.getItem(localStorage.key(i))
});
}
}
return notes;
}
function deleteNote(dateTime) {
localStorage.removeItem('note-' + dateTime);
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Voice Controlled Notes App</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/shoelace-css/1.0.0-beta16/shoelace.css">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Voice Controlled Notes App</h1>
<p class="page-description">A tiny app that allows you to take notes by recording your voice</p>
<h3 class="no-browser-support">Sorry, Your Browser Doesn't Support the Web Speech API. Try Opening This Demo In Google Chrome.</h3>
<div class="app">
<h3>Add New Note</h3>
<div class="input-single">
<textarea id="note-textarea" placeholder="Input." rows="6"></textarea>
</div>
<button id="start-record-btn" title="Start Recording">Start Recognition</button>
<button id="pause-record-btn" onClick="myFunction()" title="Pause Recording">Stop listening</button>
<p id="recording-instructions">Press the <strong>Start Recognition</strong> button and allow access.</p>
</div>
</div>
<p id="demo"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="script.js"></script>
<script>
function myFunction() {
var str = document.getElementById("note-textarea").value;
if (str.includes("hello how are you")){
document.getElementById("demo").innerHTML = "hi anthony";
responsiveVoice.speak("I am good thanks, and you?");
}
}
</script>
</body>
</html>

Output of Ajax response

My jsp page contains an array of food with 4 items in it.
When the user enters a food name in the text box which exists in the array I get a output with 4 strings stating whether it is found or not.
Depending on the position of the food item in the array I get the actual answer in the respective string. If the food item entered is the 4th element in array then 4th string written by AJAX gives the correct answer.
My screenshots show the issue
showing the output in case the value entered is Samosa Pav,the second string gives the right output.
showing the output in case the value entered is misalPav,the fourth string gives the right output
What changes so I need to make to ensure that only one and the correct output is received from AJAX call?
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.jsp?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Chuff Bucket</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
%--
Document : index
Created on : 15 Dec, 2016, 7:07:55 PM
Author : KRISHNAJI
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String food = request.getParameter("food");
String foodArray[] = {"Vada Pav", "Samosa Pav", "Pav Bhaji", "Misal Pav"};
for(int i = 0; i < foodArray.length; i++)
{
if(food.equalsIgnoreCase(foodArray[i]))
{
out.println("Hey we do have " + food);
}
else if (food == "")
{
out.println("Enter a food");
}
else
{
out.println("We don't have " + food);
}
}
%>
</body>
</html>
[1]: https://i.stack.imgur.com/sBHnZ.jpg
[2]: https://i.stack.imgur.com/Xv7fG.jpg
I will just edit the important bits here:
String food = request.getParameter("food");
String foodArray[] = {"Vada Pav", "Samosa Pav", "Pav Bhaji", "Misal Pav"};
int i = 0;
for(i = 0; i < foodArray.length; i++)
{
if(food.equalsIgnoreCase(foodArray[i]))
{
out.println("Hey we do have " + food);
break;
}
else if (food == "")
{
out.println("Enter a food");
break;
}
}
if(i >= foodArray.length)
{
out.println("We don't have " + food);
}
Right, in my comment I forgot that all other conditions in your original loop will still print because of the else statement. So I now declared your counter outside of the loop and compared to the length of the array after the loop is exited. That way, if the food they entered is not found, it will only print once at the end. If input is blank, or matches a food, the conditions will be met and it will print the correct response. The counter will cease to increment and will be less than the length of the array, failing the last condition, and leaving you with only the correct response. This should answer your question fully.

How to fetch data from a database using PHP and pass it to Javascript

I am making a website using HTML, CSS, MySQL and Javascript that will allow the user to login and play a quiz, the quiz has 40 questions.
The Javascript code bellow is a countdown timer, that contains the variable named "questions" after 40 seconds, it will pass automatically to the next question.
var i = 0;
var cEl = document.getElementById('countdown');
var qEl = document.getElementById('question');
var questions = [
'Question1 ?',
'Question2 ?',
'Question3 ?',
'Question4 ?'
];
var Countdown = function (time) {
this.time = time;
this.observers = [];
};
Countdown.prototype.start = function () {
setTimeout(function () {
if (this.time-- > 0) {
this.updateObservers();
this.start();
}
}.bind(this), 1000);
};
Countdown.prototype.addObserver = function (observer) {
this.observers.push(observer);
};
Countdown.prototype.updateObservers = function () {
var i, l = this.observers.length;
for (i = 0; i < l; i++) {
this.observers[i](this.time);
}
};
function printTime (time) {
cEl.innerHTML = time + 's';
}
function nextQuestion (time) {
if (time <= 0) run();
}
function run () {
var c;
if (i < questions.length) {
qEl.innerHTML = questions[i++];
c = new Countdown(40);
c.addObserver(printTime);
c.addObserver(nextQuestion);
printTime(c.time);
c.start();
} else {
document.body.innerHTML = 'Fin du quiz';
}
}
run();
And this is the part of my "quiz.php" file where I want the questions to be inserted :
<!doctype html>
<html>
<head>
<title>
Quiz
</title>
</head>
<body class="no-scroll">
<div>
<!-- some code here -->
</div>
<!-- some code here -->
<script src="js/countdown_script.js"></script>
</body>
</html>
For now, the questions are in the following variable :
var questions = [
'Question1 ?',
'Question2 ?',
'Question3 ?',
'Question4 ?'
];
But I want to use questions and their answers that are already in a database, each question has 2 or 3 possible answers, I've read that I'm not supposed to add the php code inside of a .js file, I tried to add the questions variable in the php code bellow but it did not work :
<!doctype html>
<html>
<head>
<title>
Quiz
</title>
</head>
<body class="no-scroll">
<div>
<!-- some code here -->
</div>
<!-- some code here -->
<script src="js/countdown_script.js">
var questions = [
'Question1 ?',
'Question2 ?',
'Question3 ?',
'Question4 ?'
];</script>
</body>
</html>
What is the best way to do that in my case? Given that I'm still a beginner and I only know html, css, some javascript, php and mysql.
You need to make a small API.
Step 1. make an additional page in your application that will output clean JSON array with data from the dataabse
For example: myApiWithQuestions.php
{
questions: {
question1: {
"content":"content of the question",
"possibleAnswers":[
"something", "another answer"
]
},
question2: {
"content":"content of the question",
"possibleAnswers":[
"something", "another answer"
]
},
}}
Step 2: Make an ajax call using JQuery to look for the page you have just created
$(document).ready(){
$.ajax({
url: "myApiWithQuestions.php",
})
.done(function( data ) {
//use data as an array, iterate through it and put your questions to the DOM
});
}
On .done function continue with execution of your script
Where did you read that you're not supposed to run PHP code in Javascript?
Anyway, it doesn't really matter: you can. I do it all the time.
<script type="text/javascript" src="js/countdown_script.js">
<script type="text/javascript"><!--
var questions = [
<?php
//create and run your mysql query
//loop through your results
while($row=mysql_fetch_array($results)){
//print your results in javascript format
printf("'%s ?'\n",$row['question']);
}
?>
];
--></script>

jQuery - building dynamic if statements based on object passed as the function argument

I'm trying to build several dynamic if statements based on the definition in the argument of the function. I should be able to run them if the particular keys and vales are provided. I can read all the keys and values, but not sure how to build a code upon them.
This is the object passed as a function argument:
param = {
'fields': {
'email' : {
'match' : 'email'
},
'countAdults': {
'match' : 'number',
'range' : '1, 10'
}
}
};
//And this bit is trying to parse the object
$.each(param.fields, function(key, value){ // reading definitions from the parameter
if(name == "'+key+'") $('[name="'+key+'"]').mandatory(); // define the begining of if
$.each(param.fields[key], function(subk, subv){
+= '.'+subk+'("'+subv+'")'; // adding more to the if statement
});
});
return (all if statement);
}
After returning all of these if statements I would also like to run an else statement for default cases. I'm trying to move these bits of code from the body of a main function, to a place where you call the function, so that I wouldn't have to customize the body of the function each time.
I suggest that you instead have elements where you add a class for every validation you want to have. Like this:
<!doctype html>
<html>
<head>
<style type="text/css">
input.invalid { border: 1px solid red; }
</style>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<script>
$(function()
{
$('.email').each(function()
{
var input = $(this);
input.keyup(function()
{
validate_as_email(input);
});
});
});
function validate_as_email(input)
{
var value = input.val();
if (is_email(value))
input.removeClass('invalid');
else
input.addClass('invalid');
}
function is_email(value)
{
return value.match
(/^[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i) != null;
}
</script>
</head>
<body>
Email:<br>
<input type="text" id="email" class="email">
</body>
</html>

Categories