-1

Issue : if i call ajax function i can't able to get return value.

Below is my simple javascript and ajax file.

Javascript Ajax

<script type="text/javascript">
    function loadDoc() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                return this.responseText;
            }
        };
        xhttp.open("GET", "testAjax.php", true);
        xhttp.send();
    }
    alert(loadDoc());
</script>

PHP

<?php
    echo "Hello World !!!";
?>

Can synchronous or asynchronous concept are useful to this problem ?

Thank you.

Jaydeep Mor
  • 1,690
  • 3
  • 21
  • 39
  • check your browser console for `JS` error – urfusion Jul 08 '17 at 07:35
  • I am not getting any error getting `undefined` in alert. – Jaydeep Mor Jul 08 '17 at 07:36
  • Per [PSR-2 2.2](http://www.php-fig.org/psr/psr-2/#files), consider removing the ending `?>` if the file will contain only PHP. – bnahin Jul 08 '17 at 07:36
  • You are returning value from onreadystatechange function which is not right, and your thinking about sync/async is correct, Use this link may be it helps you: https://stackoverflow.com/questions/19298112/returning-values-from-the-event-onreadystatechange-in-ajax – Girdhari Agrawal Jul 08 '17 at 07:37
  • 4
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Jul 08 '17 at 07:38

2 Answers2

2

The problem is the asynchronous nature of ajax requests and the execution flow of code. The callback that is invoked when the conditions of onreadystatechange are met is not guaranteed to complete before the end of the main function has been reached. To achieve a return from the ajax function you need to use Promises

let oPromise = new Promise( ( resolve, reject ) => {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            resolve( this.response );
        }
    };
    xhttp.open('GET', 'testAjax.php', true);
    xhttp.send();
});

oPromise.then( ( data ) => {
  alert('Whoohoo! -> ' + data );
});

To some the syntax of the above will be unfamiliar and perhaps a little confusing - it could be rewritten in a more familar/tradional way like this:

let oPromise = new Promise( function( resolve,reject ){
    var xhr = new XMLHttpRequest();
    xhr.onload=function(){
        resolve( this.response )
    };
    xhr.onerror=function(){
        reject( this.readyState )
    };
    xhr.open('GET', 'testAjax.php', true);
    xhr.send();
});
oPromise.then( function( response ){
     alert('Whoohoo! -> ' + response );
});
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
1

You need to change your logic like this:

function doJobWhenAjaxResultIsReturned(ajaxData){
    // alrt(ajaxData);
}
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      doJobWhenAjaxResultIsReturned(this.responseText);
    }
  };
  xhttp.open("GET", "testAjax.php", true);
  xhttp.send();
}
loadDoc();

then do what you want in doJobWhenAjaxResultIsReturned().

Ala Eddine JEBALI
  • 7,033
  • 6
  • 46
  • 65