0

At the moment I am working on some application, on which I do an AJAX-request which triggers a PHP script. This script echo's and returns some stuff while it is executing. Now would it be nice to be able to display this on the frontend, before .success() is triggered. Is this possible, and if so; how?

Cheers!

Updated with some code

Ajax + Submit (js)

$('document').ready(function() {
    setAlbum.getForm.submit( function( e ) {
        setAlbum.albumSubmit( e );
        return false;
    });
});

var setAlbum = {
    getForm             : $('#albumForm'),

    createUrlList       : function() {
        var rawUrlList = setAlbum.getForm.find('#AlbumUrlList').val();
        var urlList = rawUrlList.split(/\r?\n/g);

        return urlList;
    },

    albumSet            : function() {
        var set = {
            albumName           : setAlbum.getForm.find('#AlbumName').val(),
            albumDescription    : setAlbum.getForm.find('#AlbumDescription').val(),
            albumUrlList        : setAlbum.createUrlList(),
        };
        return set;
    },

    albumSubmit     : function( e ) {
        e.preventDefault();
        console.log( setAlbum.albumSet() );

        $.ajax({
            type: 'POST',
            url: "query.php",
            data:  setAlbum.albumSet(),
            success: function(data) {
                console.log(data)
            }  
        });
    }
};

query.php (partial)

$naming = $_POST['albumName'];
$albumDescription = ['albumDescription'];
$photolist = $_POST['albumUrlList'];

$albumset = [
        'AlbumName' => $naming,
        'ItemList' => $photolist,
        'AlbumDescription' => $albumDescription
];

/** GET FILESIZE CURL **/
function getFileSize( $url ) {
    $headers = get_headers($url);
    $fileSize = -1;
    echo var_dump($headers);
    echo $url;
    foreach( $headers as $h ) {
        preg_match( '/Content-Length: (\d+)/', $h, $m );
        if ( isset($m[1]) ) {
            $fileSize = (int)$m[1];
            break;
        }
    }

    $formattedFileSize = formatSizeUnits( $fileSize );
    echo 'Filesize:: ' . $formattedFileSize;

    return $fileSize;
}

//* FILESIZE FORMATTER *//
function formatSizeUnits( $bytes ) {
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';     
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }
    return $bytes;
}

function getPhotosSize( $array, $maxSize ) {
    $photos = $array['ItemList'];

    $countTotal = sizeof($photos);

    $count = 1;
    foreach( $photos as $photo ) {
        echo '<h2>Checking filesize&hellip;</h2>';

        //  saveImage( $img, $fullpath )
        $url = $photo;
        $photocount = sprintf('%02u', $count);

        getFilesize($url);
    }
}

getPhotosSize($albumset, $maxFileSize);
Termininja
  • 6,620
  • 12
  • 48
  • 49
oceanmountain
  • 121
  • 2
  • 9

4 Answers4

1

So basically you want to have a real time log monitoring while you execute the script. You can do this in ajax but it will be a series of ajax call.

  1. Ajax call to trigger the script.
  2. An interval Ajax call that checks the status of the script. This call will be triggered by #1.
  3. You have to have a flag/response that will stop #2. Let's say in your php script you will add array("process"=> "done"). then this will be the flag in javascript to terminate the interval call.

In you PHP script side you might need to have a logger text for the messages you need to show for that execution. So instead of "echoing" these messages, you will save it in a temporary text file which will then parsed and return to the client side (#2 in the ajax call).

Another way of doing this is via sockets. Please refer to http://socket.io/. It is much more cleaner approach (I recommend). Each client (js side) can connect to a socket connection and in you php side you will just have to post a text in that socket connection and that's it! Somewhat you are mimicking a chat server-client approach.

Francis
  • 692
  • 6
  • 10
1

Yes it is possible. The flow goes like:

  • make some request to server (start job)
  • server starts background processing and update database for process data (while processing)
  • make ajax calls with certain interval to server -> server reads process data from database and returns it to browser

I have done this. For example in Drupal there is module called "Background process".

Hardy
  • 5,590
  • 2
  • 18
  • 27
0

Yes, you have to catch that returned value with function(data) inside the AJAX-request.

Jeton
  • 44
  • 7
  • I don't think it's relevant to question as i understand it – A. Wolff Mar 08 '14 at 14:04
  • $.post(http://localhost/function.php, {username: username}, function(data){ if(data.success == 'true'){ action } else{ action } }); – Jeton Mar 08 '14 at 14:06
0

EDIDTED: My previous code was not relevant as i didnt know where done() was triggered. I have updated this now.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){

      var flag = false; //means no ajax request. true means ajax request processing.

      function send_request() {

          flag = true;
          $.ajax({
              url: "http://localhost/test.html",
                //async: true,
                success: function(data) {

                    flag = false;
                    output = data;
                    alert(data);
                }
          });

      }

      setTimeInterval('startProcess()', 1000);

      function startProcess() {


            if(flag) {                  
                //request is being processed.           
            }else{

                //request ended. stop the timer

            }

      }
});
</script>
</head>
<body>
<div id="container"></div>

</body>
</html>
Abhishek Saha
  • 2,564
  • 1
  • 19
  • 29
  • 1
    This is not relevant to the question. Here done() is the same as success callback, responding to same behaviour. Success is jut call before because the promise is resolved later. – A. Wolff Mar 08 '14 at 14:26
  • I think the meaning of my question was/is not fully clear here, my apologies. What I am trying to get is respons from the php during the request, not when it is finished (so success); I think the suggestions given by @ hardy and @francis-alvin are getting me on the right track! – oceanmountain Mar 08 '14 at 14:28
  • He didnt mention where he is triggering done(). I asked this in my comment earlier. – Abhishek Saha Mar 08 '14 at 14:29