Home > OS >  Why the AJAX response is not returned from PHP side
Why the AJAX response is not returned from PHP side

Time:06-23

I am trying to get the PHP threads progress via AJAX, but the strange think I am facing right now is that any code before startPool() method can be seen in the AJAX response but not after it, would you explain to me why this is happening?

AjaxIndex.php:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="Source code generated using layoutit.com">
    <meta name="author" content="LayoutIt!">

    
    
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="css/gijgo.min.css" rel="stylesheet" type="text/css" />
    <style>
        .error {
            border: 5px solid red !important;
        }
        
        .download-link {
            color: #26c605;
        }
        
        .download-error {
            color: #f20404;
        }
        
    </style>
  </head>
  <body>

    <div >
    <div >
        <div >
            <form id="county-form" role="form" autocomplete="off">
                <div >
                     
                    <label for="courtHouse">
                        Choose an action to scrap:
                    </label>
                    <select id="courtHouse" name="get-data" >
                        <option value="none"></option>
                        <option value="all" selected="selected">Scrap.</option>
                        <option value="force">Force scrap.</option>
                    </select>
                </div>
                
                <button id="scrape-button" type="button" >
                    Scrap now
                </button>
                <p id="result"></p>
            </form>
        </div>
    </div>
</div>

    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/gijgo.min.js" type="text/javascript"></script>
    <script src="js/scripts.js"></script>
    
    <script>
        
        $(document).ready(function() {
            let result_label = $("p#result");

            $("button#scrape-button").on('click', function(e){
                e.preventDefault();
                
                result_label.removeClass('download-error').html('');
                
                if($('#courtHouse option:selected').text() === '') {
                    $("#courtHouse").css("border", "2px solid red");
                    $("#courtHouse").focus();
                    return;
                }
                
                $("#courtHouse").css("border", "0.916667px solid rgba(0, 0, 0, 0.15)");
                $("#courtHouse").focus();
                
                result_label.html('<b>Please don\'t close the browser until the link appears here.</b>');
                const formData2 = $("#county-form").serialize();
                let last_response = '';
                $.ajax({
                    //url: "testAJAX.php",
                    url: "AjaxThread.php",
                    method: 'POST',
                    data: formData2,
                    dataType: 'text',
                    //contentType: 'application/json',
                    encode: true,
                    xhrFields: {
                        onprogress: function(e) {
                            let response = e.target.response.replace(/\n/g, '').split("|").slice(0, -1).pop();
                            //console.log('response split: ', e.target.response.replace(/\n/g, '').split("|").slice(0, -1));
                            console.log('response pop: ', response);
                            //console.log('response pop: ', JSON.parse(response).replace(/\n/g, ''));
                        }
                    },
                    success: function (result, status, xhr) {
                        console.log('success step');
                        console.log(result.status);
                        if(result.status === 'success') {
                            result_label.html(result.data);
                        }
                        else {
                            result_label.removeClass('download-link').addClass('download-error').html(result.data);
                        }
                    },
                    error: function(request, status, error) {
                        result_label.removeClass('download-link').addClass('download-error').html('Internal error, please contact the support.');
                        console.log('error step');
                        //console.log(JSON.stringify(request));
                        console.log(request);
                        console.log(status);
                        console.log(error);
                    }
                });
                
                
            });
        });
    </script>
  </body>
</html>

AjaxThread.php:

<?php

    require_once __DIR__ . '/vendor/autoload.php';


    use \ByJG\PHPThread\ThreadPool as ScrapperPool;

    try {
        $scrapper_pool = new ScrapperPool();
        for($i = 0; $i < 10;   $i) {
                $rfc_scrapper = new ScrapperThread($i);
                $scrap = function(ScrapperThread $instance) { 
                    return $instance->scrap(); 
                };
                $scrapper_pool->queueWorker($scrap, [$rfc_scrapper]);
        }

        $scrapper_pool->startPool();
        $scrapper_pool->waitWorkers();

        // Get results
        file_put_contents('AjaxThreadCount', count($scrapper_pool->getThreads())); //
        foreach($scrapper_pool->getThreads() as $worker) {
            echo($scrapper_pool->getThreadResult($worker));
        }
    }
    catch(Exception $e) {
        echo $e->getMessage();
    }
?>

CodePudding user response:

Change this line: for($i = 0; $i < 10; $i) {

to for($i = 0; $i < 10; $i ) {

CodePudding user response:

I tried the byjg/phpthread/ library using PHP parallel instead of the also included ForkHandler using pthreads and it seems to be working. Seems to be an error with the included ForkHandler/pthreads implementation somehow.

You can install parallel module from here: https://github.com/krakjoe/parallel

One of the lasts commits values the parallel module above others, so I recommend giving it a try: https://github.com/byjg/phpthread/commit/238e3dc90d439eb2145178b40c7e744f3cbdf671

Pthreads runs into an exit(0) in ForkHandler.php

There is an exit(0) in ForkHandler.php and it got triggered even when running the example in the readme of the git repository. This should give you enough reason to try parallel extension.

CodePudding user response:

Check if this helps

<?php

    require_once __DIR__ . '/vendor/autoload.php';


    use \ByJG\PHPThread\ThreadPool as ScrapperPool;

    try {
        $scrapper_pool = new ScrapperPool();
        for($i = 0; $i < 10;   $i) {
                $rfc_scrapper = new ScrapperThread($i);
                $scrap = function(ScrapperThread $instance) { 
                    return $instance->scrap(); 
                };
                $scrapper_pool->queueWorker($scrap, [$rfc_scrapper]);
        }

        $scrapper_pool->startPool();
        $scrapper_pool->waitWorkers();
        $result_getThreads = $scrapper_pool->getThreads();
        // Get results
        file_put_contents('AjaxThreadCount', count($result_getThreads)); //
        if($result_getThreads){
            foreach($result_getThreads as $worker) {
                echo($scrapper_pool->getThreadResult($worker));
            }
        }else{
            echo 'Something went wrong';
        }
        
    }
    catch(Exception $e) {
        echo $e->getMessage();
    }
?>
  • Related