I'm building a small quiz. The score is stored in a variable quizScore - each question on the quiz is output using AJAX. The single AJAX call grabs the ID of the button pressed (so, on question 2, the button ID is 2a which takes you to the next AJAX refresh of question2a.php)
On the last AJAX call, which calls up a file called questionendQuiz.php, I want to have the output of the variable quizScore. I need to bind this output to an event, so success of loading that through AJAX makes sense.
/* Output score */
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quizWrapper").innerHTML=xmlhttp.responseText;
if (buttonID == "question_endQuiz") {
document.getElementById("scoreOut").innerHTML = quizScore;
}
}
So this should output quizScore into div id="scoreOut" when the successful AJAX content loads.
I've double checked the score is actually working by using console logs. It is building the score correctly (see here it outputs the score in the console http://francesca-designed.me/quiz/quiz.php
I can't work out what is wrong with the success if statement to cause it to not output the score?
AJAX request, I've omitted some things that aren't useful to this question like the correct answer scoring and the start of the quiz:
/* Quiz Score */
var quizScore = 0; /* Takes you to each next question, based on ButtonID */
function nextQuestion(buttonID) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("quizWrapper").innerHTML = xmlhttp.responseText;
}
}
var splitID = buttonID.split('_');
var questionID = splitID.pop();
xmlhttp.open("GET", "question" + questionID + ".php", true);
xmlhttp.send(); /* Output score */
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("quizWrapper").innerHTML = xmlhttp.responseText;
if (buttonID == "question_endQuiz") {
document.getElementById("scoreOut").innerHTML = quizScore;
}
}
}
The button that marks the end of the quiz is:
<button id="question_endQuiz" onClick="nextQuestion(this.id)">See your score</button>
The score recording part should go into onreadystatechange as well. It is the callback for the request, and gets executed after the response is received, rather than before as in the code you provided.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("quizWrapper").innerHTML = xmlhttp.responseText;
if (buttonID == "question_endQuiz") {
document.getElementById("scoreOut").innerHTML = quizScore;
}
}
}
Related
I am facing some unidentified issue. please any one help me to sort out.
problem is when runonload() function runs, we will get print but I am getting duplicate prints (with same data). but this function executes one time (logs in this function write one time) but fnQrCode() & fnBuildBody() calling twice (logs in these function writes twice and getting prints twice). there is no loop for second time. Below is my code snippet.
var xmlcodebar="";
---
---
function runonload(){
code for print preparation
-------
-------
fnQrCode(dealref,sterlingQR, deliveryType); //this function for qr code generation
xmlcodebar = "data:image/png;base64,"+xmlcodebar;
footer11 = '<td width="100%"><img src='+xmlcodebar+' align="center" width="750" height="150"></td>';
footer12 = '</tr></table>';
fnBuildBody(strRows,strPrintData, Number(strPageLength),footer1,footer2, footer3, footer4, footer5, footer6, footer7, footer8,footer9, footer10, footer11, footer12); //this function for printing
-------
--------
}
function fnQrCode(dealref,sterlingQR,deliType){
var data =sterlingQR+";"+dealref+"$;"+deliType;
var strQueryString = "hdnOptPage=QRCODE&DATA="+data;
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Browser doesn't supports Http Request");
return;
}
var url = "<%=CONTROLSERV_TFROUT%>"+"?"+strQueryString;
xmlHttp.onreadystatechange = stateBarcode;
xmlHttp.open("POST",url,false);
xmlHttp.send();
}
function stateBarcode() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
if(xmlHttp.status == 404 || xmlHttp.status == 500){
alert("Problem occured at server. Please try again.");
window.event.returnValue=false;
return;
} else if (xmlHttp.status == 200) {
xmlcodebar = xmlHttp.responseText;
}
}
}
function GetXmlHttpObject() {
var objXMLHttp = null;
//check whether browser supports HttpRequest
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return objXMLHttp;
}
Currently, I cannot load the second content using ajax. Actually, I have loaded the first content using ajax. In order to go to the second content, i need to call the ajax function but after i click to load the second content using ajax it does not work. I have checked my code, its working fine if i directly call the second ajax function, unless i call the first ajax function after that the ajax is not working again. Are there any ways to solve this problem.
This is the first ajax code:
function showMusic(str) {
if (str == "") {
document.getElementById("albums").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("albums").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAlbums.php?q="+str,true);
xmlhttp.send();
}
}
The above function works. The above function is at another php file
This is the second ajax code:
$(document).ready(function(){
function showArtistDetails(str) {
if (str == "") {
alert("hi");
document.getElementById("artist").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
alert("hi1");
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
alert("hi2");
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("artist").innerHTML = xmlhttp.responseText;
alert("hi3");
}
};
xmlhttp.open("GET","getArtist.php?title="+str,true);
alert("hi4");
xmlhttp.send();
alert("hi5");
}
}
$("#clickme").click(showArtistDetails);
});
This is the php code which is at another php file:
echo "<td id=\"clickme\">" . $row['CDTitle'] . "</td>";
I have been trying to solve this for the past 2 days but i am unable to solve it. Some are saying its a bug. But i really i dont know what causes this problem. Thanks in advance.
I have an ajax function on my website which calls a cgi script. infrequently, this script returns a 500 error. I am trying to change the AJAX call so that when this happens, it will repeat the request. I have tried to do that as follows:
function shelverx() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//process data if successful...
} else if (xmlhttp.status == 500) {
limit++;
if (limit < 5) {
shelverx(usershelf);
}
}
}
xmlhttp.open("POST", filepath, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(postdata);
}
I'm wondering if there is a better way to accomplish this? I find that what happens is that whenever there is a 500 error, the shelverx function is called four times, even if the second call is successful. Is there a way to repeat the call only once per error?
I also tried to accomplish the same thing by changing the entire ajax call to jQuery and using the following error function:
error: function(xhr, textStatus, errorThrown ) {
this.tryCount++;
if (this.tryCount<=this.retryLimit) {
$.ajax(this);
return;
}
But I got an Unexpected Token : error. If anyone could help me to get either of these methods to work I would appreciate it greatly. My goal is to have the ajax call repeat only once per 500 error.
Jonathan -
The code snippet below works as you want. The counter holds its value between calls and stops requests at 5. I also changed the IF statement logic and added a timer to wait 1 second between tries. Give it a try.
Note that the original logic doesn't work correctly. In the debugger it was incrementing the counter multiple times per each request. Much better to check status after readyState = 4.
Original Code:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//process data if successful...
} else if (xmlhttp.status == 500) {
limit++;
if (limit < 5) {
shelverx(usershelf);
}
}
Tested and working example:
<!doctype html>
<html>
<body>
<script type="text/javascript">
var postdata = '';
var filepath = 'NothingHere.html';
var limit = 0;
function shelverx() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
console.info('Success: Recieved ' + xmlhttp.responseText.length + ' bytes');
}
else {
limit++;
console.info( 'Error: ' + xmlhttp.status + ':' + xmlhttp.statusText );
if (limit < 5) setTimeout( shelverx, 1000 );
}
}
}
xmlhttp.open("POST", filepath, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(postdata);
}
shelverx();
</script>
</body>
</html>
I am making a javascript function call on onclick of any checkbox like this:
function getPGCountList(pageNo) {
var url = "someJsp.jsp?" + pageNo;
alert(1);
if (window.XMLHttpRequest) {
alert(2);
xmlhttp = new XMLHttpRequest();
} else {
alert(3);
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
alert(4);
xmlhttp.onreadystatechange = function () {
alert(5);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(6);
document.getElementById("searchForPage").innerHTML = xmlhttp.responseText;
}
};
alert(7);
xmlhttp.open("GET", url, true);
alert(8);
xmlhttp.send();
}
The alert output I am getting is at my hosted site:
1-2-4-7-5-8-5-5-5
But in my local system it is:
1-2-4-7-5-8-5-5-5-6
I need to execute alert 6 also to change the content.
I am not sure where is the problem?
Your code looks fine to me. Check the path to someJsp.jsp
It's obviously not returning a normal response from the ajax call otherwise it would enter your if block and fire alert 6.
Just a thought too, but if you alert xmlhttp.readyState and xmlhttp.status maybe it'll help you find your problem. IF they are undefined, or refer to an object that is undefined, then your new XMLHttp requests failed. IF they give you results, you can see what the responses mean
function ajax_request(destination_full_url) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("response: \n" + xmlhttp.responseText);
return xmlhttp.responseText;
}
}
xmlhttp.open("GET", destination_full_url, true);
xmlhttp.send();
}
function third_party_function(obj) {
var response
response = ajax_request("info.php?keyword=obj.value");
alert(response);
}
<textarea onkeypress="third_party_function(this);"></textarea>
First comes off message box "underfined" one second after comes off message box with ajax request.
Question is why it runs alert(response); before finishing the previous step and how i make it wait untill ajax_request() function finished before going to next line?
because ajax is asynchronous and runs in background by default, you can make it synchronous by changing from
xmlhttp.open("GET", destination_full_url, true);
to
xmlhttp.open("GET", destination_full_url, false);
=== update ===
function ajax_request(destination_full_url, callback){
.....
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("response: \n" + xmlhttp.responseText);
callback(xmlhttp.responseText);
}
}
...
}
....
function third_party_function(obj) {
ajax_request("info.php?keyword=obj.value", function(response){alert(response) });
}