I have a function, practiceTest, ran in my view that I want to set up an event handler on for the keyup event. If the key pressed is equal to 'f' or 'j' it then checks if that is the correct answer, at which point, if it is, it performs a series of action. If not, I wanted it to send the variable 'incorrect' back to the controller, where it will be redirected to another page. The problem that is occuring is that the it seems to continuously cycle back to my practiceTest controller, as if the answer was incorrect, but it does so before an event even occurs. Nothing shows in the browser, and the Network tab in Chrome Develper tools just shows a continous cycle to the PracticeTest controller. Any ideas?
practiceTest function:
function practiceTask(counter, test_key, test_id){
setTimeout(function(){ display(counter, test_key)}, 500);
function display(counter, test_key){
$('#imageLocation').attr("src", 'sample');
$('#imageLocation').show();
start = new Date();
$(document).on("keyup", function(e){
guess = String.fromCharCode(e.which).toLowerCase();
if (counter < test_key.length){
if (guess == 'f' || guess == 'j'){
if (guess == test_key[counter].answer){
console.log(counter);
console.log(test_key[counter]);
$(document).off('keyup');
$('#imageLocation').hide();
counter++;
practiceTask(counter, test_key, test_id);
}
else{
$.ajax({
type: "POST",
url: '<?php echo site_url('practiceTest'); ?>',
data: {incorrect: 1},
success: function(data){
console.log(data);
}
});
<?php redirect(site_url('practiceTest'), 'refresh') ?>;*/
}
}
}
});
}
}
PracticeTestController:
class PracticeTest extends CI_Controller{
function index(){
$this->load->model('sample_practice');
$incorrect = $this->input->post('incorrect');
$data['incorrect'] = $incorrect;
$test_id = 1;
if ($incorrect){
$this->load->view('practice_incorrect_view.php', $data);
}
else{
$json_key = $this->sample_practice->getKey($test_id);
$json_key = json_decode($json_key, true);
shuffle($json_key);
$data['test_key'] = $json_key;
$data['test_id'] = $test_id;
$this->load->view("practice_test_view.php", $data);
}
}
}
Thank you for any help. Any ideas on how to better implement this are always appreciated as well.
EDIT:
If I use
window.location.href = '<?php echo site_url('practiceTest'); ?>';
inside of the success function in the AJAX call, it works, but then in the controller, the conditional that checks to see if $incorrect == 1 doesn't seem to working. The controller loads the practice_test_view, and not the practice_incorrect_view.
SOLUTION:
At least for my instance, by applying what I said in the EDIT above, but redirecting to a different function in the controller, and that function pointed to the practice_incorrect_view that I wished to display, it worked.