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

Error: The if statement is not providing a valid output

I am currently developing a basic price calculator that calculates the total area based on user input fields. While most of the program is functioning correctly, I am encountering an issue with the if statement that is supposed to determine the price rat ...

Updating a Parent component from a Child component in React (Functional Components)

My functional component RoomManagement initiates the fetchRooms function on the first render, setting state variables with data from a database. I then pass setLoading and fetchRooms to a child component called RoomManagementModal. The issue arises when t ...

Creating a Javascript Polling feature in a Ruby on Rails application

I'm completely new to using javascript and I am currently working on implementing polling in a rails application to display a simplified feed of activities from an activity model. I am closely following the Railscast tutorial on polling which can be f ...

Looking to validate an ajax timeout scenario

I'm currently working with an ajax call that has a timeout callback handler, and I need to find a way to test this condition. However, I am drawing a blank on how to force my application to reach that state. Any ideas or suggestions would be greatly a ...

What is the best way to manage asynchronous data within AngularJS directives?

Having encountered similar challenges to this specific scenario, I am currently facing issues with handling asynchronous data within my directives. The main issue arises when trying to pass asynchronously fetched data into these directives. Initially, I at ...

Mastering the use of expressions in ng-click and ng-show in AngularJS

I've been working on creating expandable rows within a table, but I'm encountering some issues. Despite not receiving any error messages, the functionality isn't behaving as expected. I suspect there might be an issue with how I'm using ...

The crosshair functionality in Zing Chart is causing a CPU leak

After enabling the crosshair feature on my chart, I noticed a significant issue when using Chrome 57 (and even with versions 58 and ZingChart 2.6.0). The CPU usage spikes above 25% when hovering over the chart to activate the crosshair. With two charts, th ...

The Firefox Nightly Android add-on content script will only load when the add-on popup is opened

After creating an add-on that manipulates a specific site's HTML based on user settings in the add-on's 'popup', I encountered an issue. The add-on is supposed to run a continuous content script when the user opens the site, but it only ...

Checkbox not appearing in datagrid when using Material-UI

There are some key code snippets related to the datagrid below const apiRef = React.useRef(null); const [gotApiRef, setGotApiRef] = useState(false); const [gotApiRef2, setGotApiRef2] = useState(false); console.log("apiRef.current: ", apiR ...

HTML table row content should be aligned to the left side

I am attempting to align the data in the 'Address' column without any margin. I want it to start from the left since it's overflowing. You can find the HTML, CSS, and JS code here Even though I tried using <td align="left">..</td& ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Retrieving DOM Element in Angular from Freshly Loaded Template

Recently starting my journey with Angular, I have encountered a challenge when trying to access the DOM from a newly loaded template. Let me explain what's going on - index.html <div class="template" ng-app="myApp" ng-controller="myController"> ...

Optimal method for incorporating Django with an Ajax framework

When it comes to integrating javascript libraries with a Django application, the options are abundant and diverse. Personally, I am leaning towards utilizing jQuery due to its popularity and robust features, although I am open to exploring other alternativ ...

Every time I attempt to build a React application, I encounter the same error message. I even checked the log file, but it keeps showing the proxy error

An error occurred in the command prompt while installing packages. This process may take a few minutes. Installing react, react-dom, and react-scripts with cra-template... Error: ERR_SOCKET_TIMEOUT The network encountered a socket timeout while trying to ...

Is it possible to replace the catch function in JavaScript with a custom function?

Below is the code snippet: function xyz() { try { var a = someexecutions(); handlesuccess(a) } catch (err) { handleerror(err) } } This type of function is repeated numerous times in my codebase and I am looking for a way to improve it. f ...

Shader customization and dynamic window resizing with Three.js

Having trouble with resizing the Three.js shader scene using ThreeX to handle window resizing and changing orientation on mobile devices. When the window width is decreased, everything works perfectly. However, expanding the window either in width or heigh ...

Struggling to make dynamically created SVG 'use' elements function properly

SVG offers a unique system with symbol and use where icons can be defined once and reused throughout the SVG using use. However, I am having trouble getting it to work from JavaScript. You can view an example on this JSFiddle link. When programmatically ...

Having trouble establishing a connection with Mongo.Client on localhost 27017 for MongoDB

Encountering issues with connecting to MongoDB database and storing data in localhost:27017 using MongoClient. Unable to display connection results in the console for both successful and failed connections. var express = require('express'); var r ...

stopPropagation() halts the propagation in the opposite direction

I encountered an issue while attempting to create a non-clickable div. While it does stop propagation, it doesn't prevent what should be stopped and allows things that shouldn't be clickable. js //screen has set stopPropagation $("#smokeScree ...

Updating a Texture Image in Three.js

I'm currently working on a minecraft texture editor using three.js, with a similar interface to this. My goal is to implement basic click-and-paint functionality, but I'm facing challenges in achieving this. I have textures for each face of every ...