Stop the setTimeout function after redirecting in the controller

I am experiencing an issue with my AJAX call as it keeps triggering my controller repeatedly.

AJAX function

<script type="text/javascript>
 var stopTime =0;
 var scoreCheck =  function ()
    {
      $.ajax({
      url: "<?php echo 'http://127.0.0.1/ProgVsProg/main/checkScore'?>",
      success:function(output){
        if(output){
          $('#maincontent1').html(output);
          clearTimeout(stopTime);
            }
        else{
          stopTime = setTimeout(scoreCheck, 1000);   
            }
    }
  });
}
stopTime = setTimeout(scoreCheck,3000);
</script>

Controller

public function checkScore(){
    $id = $this->session->userdata('userID');
    $battleID = $this->lawmodel->getBattle($id);
    foreach($battleID as $row){
        $Rscore = $row->requestedScore;
        $Cscore = $row->challengerScore;
        if($Cscore=="1"){
                redirect('main/secondRound');
            }
        else if($Rscore == '1'){
            redirect('main/secondRound');
        }
    }
}

Here is my secondRound function

public function secondRound(){
    $category = 'medium';
    $data['results'] = $this->lawmodel->roundTwoQuestion($category);
    $data['content'] = 'battlePage';
    if($this->session->userdata('is_logged_in'))
    {
        $this->load->view('includes/template2',$data);
    }
    else
    {
        redirect('main/restricted');
    }
}

The challenge I'm facing is how to halt the AJAX call after the initial redirect. I have set up a setTimeout function to continuously check for changes in the database and redirect to another controller upon detection of change. In my model roundTwoQuestion(), a random database entry is queried with a limit of 1.

In my view, it constantly redirects and refreshes with new data from roundTwoQuestion. Any assistance would be greatly appreciated as I am relatively new to working with AJAX. :(

Answer №1

If your controller function is named "CheckScore", then you should return a check status and test it within the success AJAX callback. After that, call another function or use JavaScript to redirect if the status is true:

Implementing AJAX Function

<script type="text/javascript>
 var stopTime = 0;
 var scoreCheck =  function () {
      $.ajax({
      url: "<?php echo 'http://127.0.0.1/ProgVsProg/main/checkScore'?>",
      success:function(output) {
        if(output === "OK") {
          clearTimeout(stopTime);
          
          // You are now free to redirect in any way you prefer
        }
        else {
          // The check returned a false status, so keep executing this function
          stopTime = setTimeout(scoreCheck, 1000);   
        }
    }
  });
}
stopTime = setTimeout(scoreCheck,3000);
</script>

Controller Code

public function checkScore(){
    $id = $this->session->userdata('userID');
    $battleID = $this->lawmodel->getBattle($id);

    // Perform necessary checks based on DB result here
    echo ($status) ?"OK" : "KO"; 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to provide an accessible title to an SVG icon using a tooltip in MUI?

When a tooltip is used with an icon button, the button automatically takes on the accessibility name of the tooltip title. This setup, as demonstrated in the documentation example, ensures that a screen reader announces it as "Delete, button", which is ben ...

Looking for a sophisticated approach in Spring MVC to manage the escaping and unescaping of strings being passed to the Front End

Currently, I am in the process of developing a web application utilizing Spring MVC. This project involves retrieving multiple objects from the Database, each containing strings as attributes. It's worth noting that I have no control over the format o ...

Contrasting images showcasing Headless vs Non Headless settings in Puppeteer

I'm currently attempting to capture a screenshot or PDF of the content available at this URL. When using the option {headless: false}, the screenshot is generated correctly; however, in headless mode, some images do not render in the screenshot (for e ...

Mastering the art of scrolling and selecting items concurrently using the mouse in Vue

Struggling with a fascinating challenge of scrolling while selecting items using mouse drag in both up and down directions. Here's a screenshot for reference: https://i.stack.imgur.com/giMwY.png Check out my code: https://codesandbox.io/s/select-i ...

Dealing with multiple submit buttons in a form with Angular JS: best practices

I'm using AngularJS and I have a form where the user can enter data. At the end of the form I want to have two buttons, one to "save" which will save and go to another page, and another button labeled "save and add another" which will save the form an ...

How to implement PayPal integration in PHP

I am currently working on integrating the paypal payment system into a website dedicated to pet adoption. Initially, I had a basic code structure that was functional. However, after making some modifications and additions to the code, it no longer redirect ...

Issues with nested array filtering in JS/Angular causing unexpected outcomes

I am faced with a particular scenario where I need to make three HTTP requests to a REST API. Once the data is loaded, I have to perform post-processing on the client side. Here's what I have: An array of "brands" An array of "materials" An array o ...

Incorporate audio playback on image click using JavaScript, with the feature to automatically pause the playback if multiple images are playing simultaneously

<img class="cl" src="photo/198.jpg"/></br> <audio class="cs" controls> <source src="audio/198 banu nagamothu.mp3" type="audio/mpeg"> </audio> I prefer not to have audio controls initially, but when the image i ...

Updating content with jQuery based on radio button selection

Looking for assistance with a simple jQuery code that will display different content when different radio buttons are clicked. Check out the code here. This is the HTML code: <label class="radio inline"> <input id="up_radio" type="radio" n ...

Building a Mongoose Schema with an Array of Object IDs: A Step-by-Step Guide

I created a user schema using mongoose: var userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true}, password: { type: String, required: true}, name: { first: { type: String, required: true, trim ...

I'm curious about the meaning of "!" in pseudo-code. I understand that it represents factorial, but I'm unsure of how to properly interpret it

Can someone explain the meaning of ! in pseudo-code to me? I understand that it represents factorial, but for some reason I am having trouble translating it. For example: I came across this code snippet: if (operation!= ’B’ OR operation != ’D’ O ...

Observing the data retrieved from an AJAX request

Currently, I have this AJAX call in my code: $('#search').keyup(function() { $.ajax({ type: "GET", url: "/main/search/", data: { 'search_text': $('#search').val() }, suc ...

`A dynamically captivating banner featuring animated visuals created with JQuery`

I am currently in the process of designing a banner for the top of my webpage, but I have yet to come across any code that meets all my requirements. To provide clarification, I have attached an illustration showcasing what I am aiming to achieve. 1) The ...

Dynamic Menu Navigation (No Bootstrap Required)

My Navbar is working perfectly in the original mode but when the screen width is less than 950px, it displays the buttons stacked vertically. However, the dropdown button opens the dropdown content on the wrong side. I want the dropdown content to appear u ...

Access model information from a controller with the help of Next.js and Sequelize

I'm currently working on a project involving Vue.js as my frontend and Next.js as my backend. While everything seems to be running smoothly, I am facing an issue with retrieving my model data back to my controller... Additional details: I have utili ...

When selecting an option triggers a pop-up in JavaScript

Implementing javascript and HTML. Consider this example: <select name='test' > <option value='1'> <option value='2'> <option value='3'> </select> If the user selects optio ...

Utilizing RxJS finalize in Angular to control the frequency of user clicks

Can someone provide guidance on using rxjs finalized in angular to prevent users from clicking the save button multiple times and sending multiple requests? When a button click triggers a call in our form, some users still tend to double-click, leading to ...

Trouble arises when attempting AJAX call to PHP file resulting in failed MySQL execution accompanied by errors

Having some trouble identifying the issue here. It seems quite simple, but I'll highlight it here anyway. On a basic website, I have a form for user registration where I'm using AJAX to send data to register.php. The form and AJAX code are as fol ...

Having trouble changing the chosen selection in the material UI dropdown menu

I've encountered an issue with my material ui code for a select dropdown. It seems that the selected option is not updating properly within the dropdown. <FormControl variant="outlined" className={classes.formControl}> <InputLabel ref={ ...

Get rid of the seconds in the output of the toLocaleTimeString

The method Date.prototype.toLocaleTimeString() provides a language-sensitive representation of the time part of a date in modern browsers. Unfortunately, this native function does not offer an option to exclude the display of seconds. By default, it shows ...