I want the user to type an answer (‘zebra’) in the input area. If they get it correct, then they are alerted that it is correct.
This answer will be pulled from a database eventually. For this simple example, I’m just pulling it into the object from another php file via jQuery AJAX.
It seems to pull in the php variable okay, but it still says ‘incorrect answer’ in the example I’m doing here =
https://michael-r-oneill.ie/development/random/Testing/testing.php
https://michael-r-oneill.ie/development/random/Testing/collectDataTesting.php
Below is the html / php file
<!-- head -->
<head>
<!-- jQuery library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js">
</script>
<title>Testing</title>
</head>
<script>
var AnswerSubmitted;
var quizes;
function quizesFunction(animal)
{quizes = [{bigPicture: animal},{bigPicture: 'tokyo'}]}
$(function() {
$.ajax({type: "POST",
url: 'collectDataTesting.php',
data: {},
dataType: "text",
success: function(data) {
quizesFunction(data);
}
});
$(document).on('click', '.submit', function() {
AnswerSubmitted = $('#typedAnswer').val();
if (AnswerSubmitted == quizes[0].bigPicture)
{
$('.test').html('correct answer').css("color", "green");;
$('.AnswerSubmitted')
.html('Answer submitted is ' + AnswerSubmitted);
$('.objectProperty')
.html('Object property is now ' + quizes[0].bigPicture);
}
else
{
$('.test').html('incorrect answer').css("color", "red");
$('.AnswerSubmitted')
.html('Answer submitted is ' + AnswerSubmitted);
$('.objectProperty')
.html('Object property is now ' + quizes[0].bigPicture);
}
});
});
</script>
<p class="objectProperty"></p>
<p class="AnswerSubmitted"></p>
<p class="test"></p>
<input type="text" id="typedAnswer" />
<button class="submit" id='AS'>enter</button>
Below is the ‘collectDataTesting.php’ php file I’m going to to collect the data
<?php
echo 'zebra';
?>
2
Answers
So as recommended by a contributor above, I managed to begin solving this issue by replying back to AJAX with JSON.
Here are the updated testing pages =
https://michael-r-oneill.ie/development/random/Testing/testing3.php
https://michael-r-oneill.ie/development/random/Testing/collectDataTesting3.php
and code below =
html =
js =
external page ('collectDataTesting3') =
If I am reading this right, then it looks like the
data
passed toquizesFunction(data)
when the ajax request is completed is not of the type that you expect.Remember that if you don’t provide the
dataType
setting to $.ajax (which you don’t), jQuery will try to “guess” the type for you (https://api.jquery.com/jQuery.ajax/).You can either set the
dataType
totext
or simply follow the advice given by the other members and have PHP return JSON (which jQuery will interpet as a JavaScript object).