Recursion with JavaScript and PHP

Recently in building an open source expense manager to replace the one I was using I encounter an interesting scenario. I wanted the application to be updated frequently. During the update process the user should be given a status update when the application is being updated. The tasks to update the application is long running but has many steps so while I might not easily be able to say how long one task will take because the server side is built using PHP I can update the user on which steps the update process was at. I set out to do this.

First Attempt

At first the update script used javascript/jquery to run multiple $.post requests and on callback run more requests. An example is shown below.

$.post(firstRequestUrl,function(){
    
    $.post(secondRequestUrl,function(){
    
       $.post(thirdRequestUrl,function(){
        
        })
    })
})

This method though easy to step up and test was clearly a waste on many levels that I spent some time thinking of a better solution. (Like 3 seconds).

This issue is actually know as callback hell. You can check out this stackoverflow question here. The solutions vary based on your usage.

A better solution

To make this process a bit cleaner I created one function that calls itself until all the steps are complete.

    var steps = ["one","two","three","four"]; // list of steps

    function runRequest(step){
        var currentStep = steps[step];
        $.post('server.php?steps='+currentStep,function(results){
            var nextStep = step+1;
            if(steps[nextStep] == null){
                // stop the recursion
            }else{
                // output results here
                runRequest(nextStep); // call the function again
            }
        });
    }

In the code above the first thing we do is list our steps. The function is called runRequest. We can call this function to get things started like

runRequest(0); // start the first request

Every time the function runs its sends a variable to the server indicating which step it is on. It then moves to the next step and calls itself until there are no more steps.

Why is this important to me

Web development and programming is often rote. Many of the things you do are more of the same. So I often get excited when I get to use knowledge I learnt in Software Engineering that I probably thought I wouldn’t need ever.

Take away

Next time to get bored during a lesson on trees and data structures in school pay attention because you might really need this information to make your work easier. You cant straight script everything in a procedural fashion that will only carry you so far. For example what is the best way to convert json to html. Data structures can save lives.

Recursion isn’t a data structure btw. I’m just saying everything comes in handy. (come on!)

Showing off our results

So lets see what our application looks like. Does it do what we want it to.

Results of demo

The sever side code

So we used the php function sleep to hold our requests by some seconds.

$step = isset($_GET["steps"]) ? $_GET['steps'] : null;

if( $step == "one" ){
    sleep(3);
    echo "Step one complete";
}else if ( $step == "two" ){
    sleep(2);
    echo "Step two complete";
}else if( $step == "three" ){
    sleep(1);
    echo "Step three complete";
}else if( $step == "four" ){
    sleep(0);
    echo "Step four complete";
}

Other simple solutions

Some other ideas include writing to a unique file or saving your updates to a database.

Conclusion

In this post we used recursion to simplify get updates from long running tasks in PHP.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s