3

How to continue run ajax call after redirect to another page in PHP?

How to go from one page to another page when Ajax call is on in PHP?

My ajax call is performing a very complex task and it will take a longtime So, Is it possible to run an ajax call after page redirect?

I make ajax call on submit button click and after that page redirects on another page and then my ajax call is Continue Running in Backend.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <title></title>
</head>
<body>
  <input type="text" name="altname" id="altname">
  <button id="btnSubmit">Submit</button>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
    $(document).on('click','#btnSubmit',function(){ 
    var altname = $("#altname").val();
        $.ajax({
            url:"http://localhost/z/backend-queue-job-php/queue_job.php",
            type:"POST",
            data:{altname:altname},
            success:function(result)
            {   
                alert(result.msg);
            }
        });
        window.location.href = "http://localhost/z/backend-queue-job-php/thankyoupage.php";
    });
}); 
</script>
JD Savaj
  • 803
  • 8
  • 16

2 Answers2

2

The simpler way to run a PHP script in background is with exec or shell_exec

You can run following function in a php file which is called via ajax, passing the path of your current script with a log path if you want to store log info:

shell_exec("/path/to/php /path/to/queue_job.php > /path_to_log/debug.log 2>&1");
prashant
  • 1,012
  • 12
  • 21
  • shell_exec("/path/to/php /path/to/queue_job.php 'alert' > in this case path in which? – JD Savaj Dec 09 '19 at 07:52
  • which path you're asking about? all must be absolute path (not URL) in above command. – prashant Dec 09 '19 at 08:03
  • you can get absolute paths of your php files as mentioned: https://stackoverflow.com/questions/11604445/php-absolute-path-to-root – prashant Dec 09 '19 at 08:04
  • this is not work i try this.... my case in first script execute , load page , script done after page is redirect so, any other idea..! – JD Savaj Dec 09 '19 at 08:43
1

It can only be done using async task in your PHP part.

  • Assign an ID for every task
  • Your ajax will create new task or fetch the status of existing task
JessGabriel
  • 1,062
  • 9
  • 18