Jump to content

ajax help


Caitlin-havener
 Share

Recommended Posts

Main html file (this will eventually contain a list of questions):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>DIG4503 - Caitlin Havener - Assignment 1</title><script type="text/javascript" src="a1.js"></script></head><body><a href="answers.txt">click here</a><div id="responseDiv"></div></body></html>

Javascript file:

function sendRequest(fileName) {    var xhr = new XMLHttpRequest();    if (xhr) {	 xhr.onreadystatechange = function() {	  displayResponse(xhr);	 }	 xhr.open("GET", fileName, true);	 xhr.send(null);    }   }   function displayResponse(xhr) {    if (xhr.readyState == 4) {	 if (xhr.status == 200 || xhr.status == 304) {	  console.log("responseText is: " + xhr.responseText);	 	  var allAnswers = xhr.responseText.split('\n');	  var numberFlag= new Array();	  for(var i=0; i<allAnswers.length; i++) {	   console.log(i + ": " + allAnswers[i]);	  	   var divideAnswer= allAnswers[i].split('*');	   console.log(divideAnswer[0] + " and " + divideAnswer[1]);	   var responseDiv = document.getElementById('responseDiv');	  //responseDiv.innerHTML = "";	  //there will prob be a 'responsediv' under each question so that there is somewhere for each answer to come up		   if (divideAnswer[1]){	   responseDiv.innerHTML += "<h3>" + divideAnswer[1] + "</h3>";	   }	  	  	   //Flag how many of each question there are	   console.log("Show me what q and i look like:" + " q" + i);	  	   //'i' below should be the length of the questions, not the answers	   if (divideAnswer[0]=="q"+ i){		 console.log("I match");		 numberFlag[i] += 1;	   }	   console.log("There are this many answers for number one:" + numberFlag[1]);	  }	 	 	 	 }	 else if (xhr.status == 404) {	  console.log("Oops, file not found!");	 }    }   }  	  window.onload = function() {    var anchor = document.getElementsByTagName('a');    anchor[0].addEventListener('click', function(e) {	 e.preventDefault();	 sendRequest(this.href);    }, false);   }     //if this.id= then look for questions that start with "q" + this.id +"*"

Answers file (this will eventually have actual answers and not giberish):

fillerq1* sldhfsdkfsdkfjsdq2* jsdfkjsdfkljsafq1* kjasdlfj

Lame part to be stuck on... if (divideAnswer[0]=="q"+ i){console.log("I match");numberFlag += 1;} I'm trying to make a counter of how many answers there are for each question (some questions will have multiple answers). The above snippet should log "I match" three times and numberFlag[1] should equal 2 and numberFlag[2] should equal 1 but it is saying the value is undefined in console. What is wrong with that snippet or am I putting var numberFlag= newArray(); somewhere wrong lol

Link to comment
Share on other sites

function sendRequest(fileName) {    var xhr = new XMLHttpRequest();    if (xhr) {	 xhr.onreadystatechange = function() {	  displayResponse(xhr);	 }	 xhr.open("GET", fileName, true);	 xhr.send(null);    }   }   function displayResponse(xhr)   {    if (xhr.readyState == 4)    {	 if (xhr.status == 200 || xhr.status == 304)	 {	  //console.log("responseText is: " + xhr.responseText);	 	  var allAnswers = xhr.responseText.split('\n');	  var numberFlag= new Array();	  var numberQuestions = 8;	  for(var i=0; i<allAnswers.length; i++)	  {	   //console.log(i + ": " + allAnswers[i]);	  	   var divideAnswer= allAnswers[i].split('*');	   //console.log(divideAnswer[0] + " and " + divideAnswer[1]);	   var responseDiv = document.getElementById('responseDiv');	  //responseDiv.innerHTML = "";	  //there will prob be a 'responsediv' under each question so that there is somewhere for each answer to come up		   if (divideAnswer[1])	   {	   responseDiv.innerHTML += "<h3>" + divideAnswer[1] + "</h3>";	   }	  	   //divideAnswer[0] is the question number  and divideAnswer[1] is the actual answer	  	  	   //Flag how many of each question there are	   for (var j=0; j<numberQuestions; j++)	   {	    if (divideAnswer[0]=="q"+ j){		  console.log("I match");		  numberFlag[j] += 1;		  // this returns a number but above returns NaN????	   --->   numberFlag[2]=1;		  console.log("There are this many answers for number one:" + numberFlag[j]);	    }	   }	  	   console.log(numberFlag.toString());	  }	 	 	 	 }	 else if (xhr.status == 404)	 {	  console.log("Oops, file not found!");	 }    }   }  	  window.onload = function()   {    var anchor = document.getElementsByTagName('a');    anchor[0].addEventListener('click', function(e)    {	 e.preventDefault();	 sendRequest(this.href);    }, false);   }     //if this.id= then look for questions that start with "q" + this.id +"*"

Now for each numberFlag[j] I'm getting NaN

Link to comment
Share on other sites

	  var allAnswers = xhr.responseText.split('\n');	  var numberQuestions = 8;	  var numberFlags = [];	  for(var i=0; i<allAnswers.length; i++){		numberFlag[i] = 0;	  		 //rest of code	  	  	   //Flag how many of each question there are	   for (var j=0; j<numberQuestions; j++){ 		  if (divideAnswer[0]=="q"+ j){			console.log("I match");			numberFlags[i]++;			console.log("There are this many answers for number one:" + numberFlags[i]);		  }		}	   console.log(numberFlags[i].toString());  }

something like that, i may not have got all the closing curl braces Edited by thescientist
Link to comment
Share on other sites

function sendRequest(fileName) {    var xhr = new XMLHttpRequest();    if (xhr) {	 xhr.onreadystatechange = function() {	  displayResponse(xhr);	 }	 xhr.open("GET", fileName, true);	 xhr.send(null);    }   }   function displayResponse(xhr)   {    if (xhr.readyState == 4)    {	 if (xhr.status == 200 || xhr.status == 304)	 {	  //console.log("responseText is: " + xhr.responseText);	 	  var allAnswers = xhr.responseText.split('\n');	  var numberFlag= [];	  	  var numberQuestions = 8;	  for(var i=0; i<allAnswers.length; i++)	  {	  	   //console.log(i + ": " + allAnswers[i]);	  	   var divideAnswer= allAnswers[i].split('*');	   //console.log(divideAnswer[0] + " and " + divideAnswer[1]);	   var responseDiv = document.getElementById('responseDiv');	  //responseDiv.innerHTML = "";		  	  	   //Write answer to appropriate question heading	  	   //responseDiv.innerHTML += "<h3>" + divideAnswer[1] + "</h3>";	    //if value of link is q1 etc then display those particular answers in particular place	   	   	    //?????AT PARTICULAR TIME	    for (var j=0; j<=numberQuestions; j++)	    {		 if (divideAnswer[0] == "q" + j)		 {		  var responseUl= document.getElementById('responseUl' + j);		  responseUl.innerHTML += "<li>" + divideAnswer[1] + "</li>";		 }			    }	  	  	  	  	   //divideAnswer[0] is the question number  and divideAnswer[1] is the actual answer	  	  	   //Flag how many of each question there are	   for (var j=0; j<numberQuestions; j++)	   {	    numberFlag[j] = 0;	    //numberFlag[j] = 0;	    if (divideAnswer[0]=="q"+ j){		  console.log("I match");		  numberFlag[j] ++;		  // this returns a number but above returns NaN????	   --->   numberFlag[2]=1;	    }	    console.log("There are this many answers for number one:" + numberFlag[j]);	   }	  	  }	 	 	 	 }	 else if (xhr.status == 404)	 {	  console.log("Oops, file not found!");	 }    }   }  	  window.onload = function()   {    var anchor = document.getElementsByTagName('a');    anchor[0].addEventListener('click', function(e)    {	 e.preventDefault();	 sendRequest(this.href);    }, false);   }     //if this.id= then look for questions that start with "q" + this.id +"*"

Link to comment
Share on other sites

var allAnswers = xhr.responseText.split('\n');var numberQuestions = 8; //loop through the questionsfor(var i = 1; i <= 8; i++){  //define a variable to map question to answers  var question = 'q' + i;  var answersPerQuestion = 0;  console.log('QUESTION => ' + question);   //loop through the answers, and split on the *  for(var j = 0; j < allAnswers.length; j++){	var line = allAnswers[j];	var pieces = line.split('*');		console.log('LINE -> ' + line);	console.log('line question => ' + pieces[0]);	console.log('line answer => ' + pieces[1]);		//determine if the current line contains	//an answer for our question	if(pieces[0] == question){	  //increment our number of answers for this question	  answersPerQuestion++; 	  //add the answer under the appropriate question in the DOM	  var output = document.getElementById('responseUl' + i);	  output.innerHTML += "<li>" + pieces[1] + "</li>";	};  };  console.log('Number of answers for question #' + i + ' => ' + answersPerQuestion);};

Edited by thescientist
Link to comment
Share on other sites

pseudocode

 var numberQuestions = 8;var numberOfQuestions= new Array(); //preload functionfunction init(){var anchor = document.getElementsByTagName('a');//set up flag for how many times a given anchor is clicked for (i=1; i<=numberQuestions; i++){anchor[i].addEventListener('click', function(e) {e.preventDefault();getAnswers(this.name);}, false); //OWEN IM HAVING THE SAME PROBLEM HERE WHERE I WANT TO USE THE ELEMENTS OF AN ARRAY AS INDIVIDUAL COUNTERS FOR EACH QUESTION... will this work?var clickCounter= newArray(); //flag to count how many times a given link is clickedclickCounter[i] = 0;}//httprequest number of questions for each question var xhr = new XMLHttpRequest(); if (xhr) {xhr.onreadystatechange = function() { displayResponse(xhr);}xhr.open("GET", "answers.txt", true);xhr.send(null);} function displayResponse(xhr) {if (xhr.readyState == 4) {if (xhr.status == 200 || xhr.status == 304) { var allAnswers = xhr.responseText.split('\n');var numberQuestions = 8; //loop through the questionsfor(var i = 1; i <= 8; i++){ //define a variable to map question to answers var question = 'q' + i; var answersPerQuestion = 0; console.log('QUESTION => ' + question);  //loop through the answers, and split on the * for(var j = 0; j < allAnswers.length; j++) {var line = allAnswers[j];var pieces = line.split('*'); //determine if the current line contains an answer for our questionif(pieces[0] == question){ //increment our number of answers for this question answersPerQuestion++; }; }; console.log('Number of answers for question #' + i + ' => ' + answersPerQuestion); numberOfQuestions[i] = answersPerQuestion; //put numbers in seperate corresponding question variables //place number in the DOM for name==questionVariable numberIntoAnchor=document.createElement(toString(numberOfQuestions[i])); getAnchors=document.getElementsByName(i)[0];getAnchors.appendChild(numberIntoAnchor);};   }else if (xhr.status == 404) {console.log("Oops, file not found!");}}}   } window.onload = init; //where to place this?  //PAGE NOW HAS LOADED WITH NUMBER OF QUESTIONS LINK NEXT TO EACH QUESTION //WHEN USER CLICKS QUESTION NUMBER FUNCTION IS CALLED W/ ANCHOR NAME AS PARAMETERfunction getAnswers(name){var nameInt = parseInt(name);//comes in as string so parseclickCounter[nameInt]++; if (nameInt % 2 != 0)//IF clickCounter[parseInt(name)] is NOT divisible by two, which means it was clicked once or third time back on { }//httprequest split questions into pieces//filter looking for name to match pieces[0]//when they match, output pieces[1] to Ul.name}  

Edited by Caitlin
Link to comment
Share on other sites

var numberQuestions = 8;var numberOfQuestions= new Array();//preload functionfunction init(){var anchor = document.getElementsByTagName('a');//set up flag for how many times a given anchor is clickedfor (i=1; i<=numberQuestions; i++){   anchor[i].addEventListener('click', function(e)   {    e.preventDefault();    getAnswers(this.name);   }, false);     //OWEN IM HAVING THE SAME PROBLEM HERE WHERE I WANT TO USE THE ELEMENTS OF AN ARRAY AS INDIVIDUAL COUNTERS FOR EACH QUESTION... will this work?  var clickCounter= newArray(); //flag to count how many times a given link is clicked  clickCounter[i] = 0;}//httprequest number of questions for each questionvar xhr = new XMLHttpRequest();if (xhr){  xhr.onreadystatechange = function()  {   displayResponse(xhr);  }  xhr.open("GET", "answers.txt", true);  xhr.send(null);}  function displayResponse(xhr){  if (xhr.readyState == 4)  {   if (xhr.status == 200 || xhr.status == 304)   {       var allAnswers = xhr.responseText.split('\n');	    //loop through the questions    for(var i = 1; i <= 8; i++){	  //define a variable to map question to answers	  var question = 'q' + i;	  var answersPerQuestion = 0;	  console.log('QUESTION => ' + question);		  //loop through the answers, and split on the *	  for(var j = 0; j < allAnswers.length; j++)	  {	  var line = allAnswers[j];	  var pieces = line.split('*');	 	  //determine if the current line contains an answer for our question	  if(pieces[0] == question)	  {	    //increment our number of answers for this question	    answersPerQuestion++;	  	  };	  };	  console.log('Number of answers for question #' + i + ' => ' + answersPerQuestion);	  numberOfQuestions[i] = answersPerQuestion; //put numbers in seperate corresponding question variables	  //place number in the DOM for name==questionVariable	  numberIntoAnchor=document.createElement(toString(numberOfQuestions[i]));	 getAnchors=document.getElementsByName(i)[0];	 getAnchors.appendChild(numberIntoAnchor);    };      }   else if (xhr.status == 404)   {    console.log("Oops, file not found!");   }  }} }window.onload = init; //where to place this?//PAGE NOW HAS LOADED WITH NUMBER OF QUESTIONS LINK NEXT TO EACH QUESTION//WHEN USER CLICKS QUESTION NUMBER FUNCTION IS CALLED W/ ANCHOR NAME AS PARAMETERfunction getAnswers(name){var nameInt = parseInt(name);//comes in as string so parseclickCounter[nameInt]++;if (nameInt % 2 != 0)//IF clickCounter[parseInt(name)] is NOT divisible by two, which means it was clicked once or third time back on{//httprequest split questions into pieces//filter looking for name to match pieces[0]//when they match, output pieces[1] to Ul.name    var xhr = new XMLHttpRequest();    if (xhr) {	 xhr.onreadystatechange = function() {	  displayResponse(xhr);	 }	 xhr.open("GET", fileName, true);	 xhr.send(null);    }     function displayResponse(xhr)   {    if (xhr.readyState == 4)    {	 if (xhr.status == 200 || xhr.status == 304)	 {	 	  var allAnswers = xhr.responseText.split('\n');	  	  //loop through the questions	  for(var i = 1; i <= 8; i++)	  {	    //loop through the answers, and split on the *	    for(var j = 0; j < allAnswers.length; j++)	    {	    var line = allAnswers[j];	    var pieces = line.split('*');	   	    //determine if the current line contains	    //an answer for our question	    if(pieces[0] == question)	    {		  //add the answer under the appropriate question in the DOM		  var output = document.getElementById(nameInt); //is nameInt what we use??		  output.innerHTML += "<li>" + pieces[1] + "</li>";	    };	    };	  };	 	 }	 else if (xhr.status == 404)	 {	  console.log("Oops, file not found!");	 }    }   }}else if (nameInt % 2 == 0){  //take the answers to each question off the page}   }

Edited by Caitlin
Link to comment
Share on other sites

<!DOCTYPE html><head>  <meta http-equiv="Content-Type" CONTENT="text/html; charset=utf-8">  <title>DIG4503 - Caitlin Havener - Assignment 1</title>  <style>  h2{    cursor: pointer;  }  li{    color: green;  }  </style>  <script>    var makeRequest = function(questionNumber){    console.log('ENTER makeRequest for question => ' + questionNumber);    var xhr = new XMLHttpRequest();    if (xhr){      xhr.onreadystatechange = function(){        if(this.readyState === 4 && this.status === 200){          console.log('SUCCESS RESPONSE => ' + this.responseText);          showAnswers(questionNumber, this.responseText.split('\n'));        };      };    };    xhr.open("GET", "answers.txt", true);    xhr.send(null);  };  var getAnswers = function(questionNumber){    console.log('ENTER getAnswers for question => ' + questionNumber);    makeRequest(questionNumber);  };  var showAnswers = function(questionNumber, allAnswers){    console.log('ENTER showAnswers for question => ' + questionNumber);    console.log(allAnswers);    //loop through the answers, and split on the *    for(var i = 0, l = allAnswers.length; i < l; i++){      var line = allAnswers[i];      var pieces = line.split('*');      console.log('LINE -> ' + line);      console.log('line question => ' + pieces[0]);      console.log('line answer => ' + pieces[1]);      //determine if the current line contains      //an answer for our question      if(pieces[0] == ('q' + questionNumber)){        //output the answer to the appropriate question        var output = document.getElementById('responseUl' + questionNumber);        output.innerHTML += "<li>" + pieces[1] + "</li>";      };    };  };  var init = function(){    console.log('ENTER init');    //get all answer links    var answerLinks = document.getElementsByTagName('h2');    //loop through these links    for(var i = 0, l = answerLinks.length; i < l; i++){      var link = answerLinks[i];      //assign an onlick listener to call a function      //make request, get answers, and show      //using closure to preserve the value of i      link.addEventListener('click', function(questionNumber){        console.log('ENTER link.click for question => ' + questionNumber);        return function(){          getAnswers(questionNumber);        };      }(i+1), true);    };  };  window.onload = init;  </script></head><body>  <h1>Q + Ajax</h1>  <h2>What school do I go to?</h2>  <ul id="responseUl1"></ul>  <h2>What am I studying?</h2>  <ul id="responseUl2"></ul>  <h2>What is my son's name?</h2>  <ul id="responseUl3"></ul>  <h2>What colors have been in my hair?</h2>  <ul id="responseUl4"></ul>  <h2>What kind of operating system is on my phone?</h2>  <ul id="responseUl5"></ul>  <h2>What kinds of soda do I like?</h2>  <ul id="responseUl6"></ul>  <h2>What are my favorite types of food?</h2>  <ul id="responseUl7"></ul>  <h2>What foreign country have I been to?</h2>  <ul id="responseUl8"></ul></body></html>

Edited by thescientist
Link to comment
Share on other sites

there is a known issue where the answers will keep showing once they are clicked after the first time. I'll leave that one up to you. You could create an array (say hasBeenAnswered) for each question during the loop, and set the index to false, and then true on click. Then have the event listener only call the getAnswers function if the question hasn't already been clicked, by checking against that value in the array.

Link to comment
Share on other sites

Could just determine how many child 'li' tags there are, if zero allow output, if more than zero disallow output
		var child_li_total = output.getElementsByTagName("li").length;		if(child_li_total <=0)		{		output.innerHTML += "<li>" + pieces[1] + "</li>";		}

but some questions have more than one answer. So wouldn't that prevent the extra answers from showing up?
Link to comment
Share on other sites

Well then all you would have to do is compare number of answers to the number of li elements

<!DOCTYPE html><head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  <title>DIG4503 - Caitlin Havener - Assignment 1</title>  <style>  h2{    cursor: pointer;  }  li{    color: green;  }  </style>  <script>    var makeRequest = function(questionNumber){    console.log('ENTER makeRequest for question => ' + questionNumber);    var xhr = new XMLHttpRequest();    if (xhr){	  xhr.onreadystatechange = function(){	    if(this.readyState === 4 && this.status === 200){		  console.log('SUCCESS RESPONSE => ' + this.responseText);		  showAnswers(questionNumber, this.responseText.split('\n'));	    };	  };    };    xhr.open("GET", "answers.txt", true);    xhr.send(null);  };  var getAnswers = function(questionNumber){    console.log('ENTER getAnswers for question => ' + questionNumber);    makeRequest(questionNumber);  };  var showAnswers = function(questionNumber, allAnswers){    console.log('ENTER showAnswers for question => ' + questionNumber);    console.log(allAnswers);var totalanswers =0; ///////////////////////////////////////////////////////////////////////////////////////////// added by dsonesuk    //loop through the answers, and split on the *    for(var i = 0, l = allAnswers.length; i < l; i++){    	  var line = allAnswers[i];	  var pieces = line.split('*');	  console.log('LINE -> ' + line);	  console.log('line question => ' + pieces[0]);	  console.log('line answer => ' + pieces[1]);	  //determine if the current line contains	  //an answer for our question	  if(pieces[0] == ('q' + questionNumber)){            totalanswers++; ///////////////////////////////////////////////////////////////////////////////////////////// added by dsonesuk	    //output the answer to the appropriate question	    var output = document.getElementById('responseUl' + questionNumber);        var child_li_total = output.getElementsByTagName("li").length; ///////////////////////////////////////////////////////////////////////////////////////////// added by dsonesuk         if(child_li_total <totalanswers)///////////////////////////////////////////////////////////////////////////////////////////// added by dsonesuk            {///////////////////////////////////////////////////////////////////////////////////////////// added by dsonesuk	        output.innerHTML += "<li>" + pieces[1] + "</li>";            }///////////////////////////////////////////////////////////////////////////////////////////// added by dsonesuk	  };     };      };  var init = function(){    console.log('ENTER init');    //get all answer links    var answerLinks = document.getElementsByTagName('h2');    //loop through these links    for(var i = 0, l = answerLinks.length; i < l; i++){	  var link = answerLinks[i];	  //assign an onlick listener to call a function	  //make request, get answers, and show	  //using closure to preserve the value of i      	  link.addEventListener('click', function(questionNumber){	    console.log('ENTER link.click for question => ' + questionNumber);	    return function(){		  getAnswers(questionNumber);	    };	  }(i+1), true);    };  };  window.onload = init;  </script></head><body>  <h1>Q + Ajax</h1>  <h2>What school do I go to?</h2>  <ul id="responseUl1"></ul>  <h2>What am I studying?</h2>  <ul id="responseUl2"></ul>  <h2>What is my son's name?</h2>  <ul id="responseUl3"></ul>  <h2>What colors have been in my hair?</h2>  <ul id="responseUl4"></ul>  <h2>What kind of operating system is on my phone?</h2>  <ul id="responseUl5"></ul>  <h2>What kinds of soda do I like?</h2>  <ul id="responseUl6"></ul>  <h2>What are my favorite types of food?</h2>  <ul id="responseUl7"></ul>  <h2>What foreign country have I been to?</h2>  <ul id="responseUl8"></ul></body></html>

Link to comment
Share on other sites

it seems like it would be easier to set a mapped (in an array) flag variable for every question, and when the answers have been output the first time, set it to true. Initialize it to false and check for that before calling the getAnswers function. Or at least that would be my implementation of something like that.

Link to comment
Share on other sites

Am I missing something here? sorry, why go through creating a array,and flagging it true false as you say seems pointless, when you have a simple solution of counting the answers and comparing it to the number of li elements to those exact number of answers. i could understand if you wanted the other answers, shown one at a time for some reason, but as far as i can work out, ALL the answers will show all at once.

Link to comment
Share on other sites

because to me its a simple case of something either being true or false. the answers have been shown or they haven't. why bother adding more counters and conditionals. You've seen the answers, so "shown" would be true. you haven't seen the answers, so shown would be false It's not like it takes an excessive amount of code to write. initialize an array, on the init loop set the current index to false, and check the flag in show answers. if we can show answers, do it. if we can't don't.

<!DOCTYPE html><head>  <meta http-equiv="Content-Type" CONTENT="text/html; charset=utf-8">  <title>DIG4503 - Caitlin Havener - Assignment 1</title>  <style>  h2{	cursor: pointer;  }  li{	color: green;  }  </style>  <script>	var makeRequest = function(questionNumber){	console.log('ENTER makeRequest for question => ' + questionNumber);	var xhr = new XMLHttpRequest(); 	if (xhr){	  xhr.onreadystatechange = function(){		if(this.readyState === 4 && this.status === 200){		  console.log('SUCCESS RESPONSE => ' + this.responseText);		  showAnswers(questionNumber, this.responseText.split('\n'));		};	  };	};	xhr.open("GET", "answers.txt", true);	xhr.send(null);  };    var getAnswers = function(questionNumber){	console.log('ENTER getAnswers for question => ' + questionNumber);	makeRequest(questionNumber);  };   var showAnswers = function(questionNumber, allAnswers){	console.log('ENTER showAnswers for question => ' + questionNumber);	console.log(allAnswers);	var questionIndex = questionNumber - 1;	//loop through the answers, and split on the *	for(var i = 0, l = allAnswers.length; i < l; i++){	  var line = allAnswers[i];	  var pieces = line.split('*'); 	  console.log('LINE -> ' + line);	  console.log('line question => ' + pieces[0]);	  console.log('line answer => ' + pieces[1]); 	  //determine if the current line contains	  //an answer for our question	  //and only show if the answers havent already been shown	  if(pieces[0] == ('q' + questionNumber) && !answersShown[questionIndex]){		//output the answer to the appropriate question		var output = document.getElementById('responseUl' + questionNumber);		output.innerHTML += "<li>" + pieces[1] + "</li>";	  };	};	answersShown[questionIndex] = true;  //set the flag to true for future events  };   var answersShown = [];  //initialize an answersShown array  var init = function(){	console.log('ENTER init');	//get all answer links	var answerLinks = document.getElementsByTagName('h2'); 	//loop through these links	for(var i = 0, l = answerLinks.length; i < l; i++){	  var link = answerLinks[i];	  answersShown[i] =  false;  //initliaze each index to false 	  //assign an onlick listener to call a function	  //make request, get answers, and show	  //using closure to preserve the value of i	  link.addEventListener('click', function(questionNumber){		console.log('ENTER link.click for question => ' + questionNumber);		return function(){		  getAnswers(questionNumber);		};	  }(i+1), true);	};  };   window.onload = init;  </script></head> <body>   <h1>Q + Ajax</h1>   <h2>What school do I go to?</h2>  <ul id="responseUl1"></ul>   <h2>What am I studying?</h2>  <ul id="responseUl2"></ul>   <h2>What is my son's name?</h2>  <ul id="responseUl3"></ul>   <h2>What colors have been in my hair?</h2>  <ul id="responseUl4"></ul>   <h2>What kind of operating system is on my phone?</h2>  <ul id="responseUl5"></ul>   <h2>What kinds of soda do I like?</h2>  <ul id="responseUl6"></ul>   <h2>What are my favorite types of food?</h2>  <ul id="responseUl7"></ul>   <h2>What foreign country have I been to?</h2>  <ul id="responseUl8"></ul>  </body></html>

To me the intent of code is a lot clearer if your just testing against a boolean value, which is half the reason I would do it anyway. I'm not saying your way is wrong, this is just my preference/style of writing code. edit: Also, you get the advantage of being able to cache this information locally, without having to reach out to the DOM everytime to check the <li>', since currently the assignment requires that the AJAX request be made everytime to fetch the answers.

Edited by thescientist
Link to comment
Share on other sites

You guys are so funny! LOL working on it this morning. Need to get it done today! MEHH
Hi Caitlin,And also, all those guys are genius as well! Hope you are doing well. Wishing you Good Luck! :)
Link to comment
Share on other sites

Am I missing something here? sorry, why go through creating a array,and flagging it true false as you say seems pointless, when you have a simple solution of counting the answers and comparing it to the number of li elements to those exact number of answers. i could understand if you wanted the other answers, shown one at a time for some reason, but as far as i can work out, ALL the answers will show all at once.
Hi dsonesuk, I am sorry if I have done something wrong to you. Still I have no idea why you have blocked me but I respect your choice. No worries. By the way I don’t have any hard feelings against. You have been so wonderful to me. Take care mate!
Link to comment
Share on other sites

Look mate! the way you keep bringing it up, time after time it looks very well that i made the right choice! and you will remain blocked. geees get over it!
Hi dsonesuk,Gotch you mate. I am getting over it. By the way I was concerned about our connection and hence I kept bringing it up, time after time. But thanks for the clarification that you made the right choice. Absolutely no worries. Good Bye and Good Luck mate!
Link to comment
Share on other sites

YAYY I got everything to work. Thank you so much! I used my own code though and implemented some of your stuff. Mine of course isn't as pretty but I didn't understand everything in yours and I had been looking at mine for so long so I just stuck to most of it

  • Like 1
Link to comment
Share on other sites

awesome, glad to hear you got it working. The most important part about programming is knowing what you're writing, and being able to say confidently what each line is doing. If you ever need elaboration or clarification on anything provided or exampled, feel free to ask and we can just chat about it too. If you feel like sharing your finished product, then that would be cool too. :)

Edited by thescientist
Link to comment
Share on other sites

YAYY I got everything to work. Thank you so much! I used my own code though and implemented some of your stuff. Mine of course isn't as pretty but I didn't understand everything in yours and I had been looking at mine for so long so I just stuck to most of it
Hi Caitlin,That's Excellent! Good Job! I think maybe my Good Luck wishes worked for you :)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...