Michael Samuel
Michael Samuel

Reputation: 3920

How to receive jQuery post response before completing execution of PHP script?

I have a simple jquery function that sends a post request to a PHP file like this:

$.post('/file.php',
{
     action: 'send'   
},

function(data, textStatus)
{     
     alert(data);
});

And a PHP file:

<?php

/* Some SQL queries here */

echo 'action done';

/* echo response back to jquery and continue other actions here */

?>

jQuery by default waits till executing the whole PHP script before giving the alert. Is there a way to alert the action done before executing the rest of the PHP file??

Thanks

Upvotes: 1

Views: 376

Answers (1)

MrCode
MrCode

Reputation: 64526

It is possible with plain Javascript ajax. The onreadystatechange event will fire with a readyState of 3, when data is received before the request is complete.

In the example below, newData will contain the new piece of data. We have to do some processing because the XHR actually gives us the entire data so far in responseText and so if we only want to know the new data, we have to keep a record of the last index.

var httpRequest, lastIndex = 0;

if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

httpRequest.onreadystatechange = function() {
    if(httpRequest.readyState === 3) {
        var newData = httpRequest.responseText.substring(lastIndex);
        lastIndex = httpRequest.responseText.length;

        console.log(newData);
    } 
};

httpRequest.open('POST', '/file.php');
httpRequest.send('action=send');

As for jQuery ajax, this answer suggests jQuery lets you bind to the readystatechange but I haven't tested it.

Upvotes: 1

Related Questions