Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call php methods from js?

I am working on project of Counter service where I need to control the flow the customers, each customer can have 5mins in the counter. On the other hand, the system should control 5 counters.

Here is my attempt to solve the problem. Look at my MWE:

 //this is part of the code where I set the timer for each counter. 
function increment() {
      if (running == 1) {
        setTimeout(function() {
          time++;
          var mins = Math.floor(time / 10 / 60);
          var secs = Math.floor(time / 10);
          var tenths = time % 10;
          if (mins == 5) {
            //after 5 mins is over the system should call php deQueue() method to dequeue the current and point out to next customer.
            document.getElementById("message").innerHTML = "Currently, Counters are available... Next Customer..."
            deQueue();
           //this is my php method.
            available();
          }
          document.getElementById("timer").innerHTML = mins + ":" + secs + ":" + tenths;
          increment();
        }, 100)
      }
}
//And this is my php file.

<?php
      	public function deQueue(){
    		if (!$this->isEmpty()) {
    			$this->front = ($this->front+1) %5;
    			$this->size--;
    		}else{
    			echo "The Counter is empty! <br>";
    		}
    	}
    
    ?>
like image 746
Muaath Alhaddad Avatar asked Jun 26 '26 19:06

Muaath Alhaddad


1 Answers

Now you will need to use an ajax request to your php file like this:

function increment() {
    if (running == 1) {
        setTimeout(function() {
            time++;
            var mins = Math.floor(time / 10 / 60);
            var secs = Math.floor(time / 10);
            var tenths = time % 10;
            if (mins == 5) ajaxDequeue(mins);
            document.getElementById("timer").innerHTML = mins + ":" + secs + ":" + tenths;
            increment();
        }, 100)
    }
}

function ajaxDequeue(mins){ 
    $.ajax({  
        url: 'ajax.php?minutes=' + mins,  
        beforeSend: function() 
        {
            document.getElementById("message").innerHTML = "Currently, Counters are available... Next Customer..."
        },  
        success: function(response)
        {
            document.getElementById("message").innerHTML = response;
        }      
    });
}

then in your ajax.php file set it to check for value of minutes

<?php
    $minutes = $_GET["minutes"];

    if (isset($minutes)) deQueue();

    public function deQueue(){
            if (!$this->isEmpty()) {
                $this->front = ($this->front+1) %5;
                $this->size--;
            }else{
                echo "The Counter is empty! <br>";
            }
        }
?>
like image 124
Jack Siro Avatar answered Jun 29 '26 07:06

Jack Siro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!