Carl Miller
Carl Miller

Reputation: 113

Can a php script called using Ajax post send back SSE events while the script executes

I have a php script on my server that performs multiple tasks (setting up folders, copying files etc) and I call the script with ajax.

i.e

signup.js:

const evtSource = new EventSource("/createuser.php", { withCredentials: true } );
evtSource.onmessage = function(event) {
  console.log(event.data);
}

$.ajax({
    type:     'POST',
    url:      '/createuser.php',
    dataType: 'json',
    data: {
        'username': "test user", 
        'usertype' : "author"
    },
    success: function(data){
        console.log("user created");
    }
});

now on createuser.php I try and send a message to my webpage:

createuser.php:

<?php
function SendProgressMessage($op){
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    switch($op){
        case "userCreated":
            echo "User Created";
        break;
        case "foldersCreated":
            echo "Folder structure created";
        break;
        case "TemplatesCopied":
            echo "Templates Copied";
        break;
    }
    flush();
}
?>

can i setup the evtSource to the same script and the ajax call or does 2 session get created to the script?

Upvotes: 0

Views: 164

Answers (1)

Honk der Hase
Honk der Hase

Reputation: 2488

You cannot set it up like this, the AJAX request will result in an new PHP process on the server side, which isn't aware of the first process.

The long-working script should store the status into a database, from where it can be queried independently by a second(, third, ...) request.

Upvotes: 1

Related Questions