最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Returning AJAX responseText from a seperate file - Stack Overflow

programmeradmin0浏览0评论

This question may have been asked a million times in the past but I am yet to e across a solution. So I ask again, hoping a less aggressive answer like "Look somewhere else" or "Don't repeat questions". If the reader feels the urge to type any of or similar to the aforementioned sentences, I can only request the reader to refrain from doing so and ignore this post pletely. Any help is greatly appreciated.

The problem

In my program, an AJAX script works to municate with a PHP script. There are no syntax errors. The AJAX receives the responseText well and alerts it out.

alert(request.responseText); //this works as desired

But fails to return it to another function.

return(request.responseText); //this actually returns undefined

The full code Client file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ".dtd">
<html xmlns="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>test</title>
<script type="text/javascript" language="javascript" src="ajax.js"></script>
<script type="text/javascript" language="javascript">

    function createXMLHttp()
    {
        var xmlHttp = null; 
        if(window.XMLHttpRequest)
        {
            xmlHttp = new XMLHttpRequest();
        }
        else if(window.ActiveXObject)
        {   
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xmlHttp;
    }

    function ajax_phprequest(data, php_file)
    {
        var request =  createXMLHttp();
        request.open("POST", php_file, true);
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send(data);
        request.onreadystatechange = function() 
        {
            if (request.readyState == 4)
            {
                document.write(request.responseText);
                return request.responseText; //changed from return(request.responseText;);
            }
        }
    }

    function foo()
    {
        alert(ajax_phprequest("user=defuser&pass=123456","auth.php"));
    }
</script>
</head>
    <input type="button" id="somebutton" value="Call foo()" onclick="foo();" />
<body>
</body>
</html>

The full code auth.php file

<?php
    $user;
    $pass;
    if (isset($_POST['user']))  $user = $_POST['user'];
    else
    {
        echo 'err_u_Username is not specified';
        exit();     
    }
    if (isset($_POST['pass']))  $pass = $_POST['pass'];
    else
    {
        echo 'err_p_Password is not specified';
        exit();
    }
    if ($user = 'defuser' && $pass = '123456') echo ('That\'s right!');
    else echo ('That\'s not right!');
?>

This can easily be solved by including the code in the same file as the document. But I wish to call the function from a different file and then return it to the file that has foo() or the document. Simply, I want the AJAX function to return the responseText without it giving an `undefined' every time. If this has anything to do with synchronization: I want to know of any workarounds against this problem.

This question may have been asked a million times in the past but I am yet to e across a solution. So I ask again, hoping a less aggressive answer like "Look somewhere else" or "Don't repeat questions". If the reader feels the urge to type any of or similar to the aforementioned sentences, I can only request the reader to refrain from doing so and ignore this post pletely. Any help is greatly appreciated.

The problem

In my program, an AJAX script works to municate with a PHP script. There are no syntax errors. The AJAX receives the responseText well and alerts it out.

alert(request.responseText); //this works as desired

But fails to return it to another function.

return(request.responseText); //this actually returns undefined

The full code Client file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>test</title>
<script type="text/javascript" language="javascript" src="ajax.js"></script>
<script type="text/javascript" language="javascript">

    function createXMLHttp()
    {
        var xmlHttp = null; 
        if(window.XMLHttpRequest)
        {
            xmlHttp = new XMLHttpRequest();
        }
        else if(window.ActiveXObject)
        {   
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xmlHttp;
    }

    function ajax_phprequest(data, php_file)
    {
        var request =  createXMLHttp();
        request.open("POST", php_file, true);
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send(data);
        request.onreadystatechange = function() 
        {
            if (request.readyState == 4)
            {
                document.write(request.responseText);
                return request.responseText; //changed from return(request.responseText;);
            }
        }
    }

    function foo()
    {
        alert(ajax_phprequest("user=defuser&pass=123456","auth.php"));
    }
</script>
</head>
    <input type="button" id="somebutton" value="Call foo()" onclick="foo();" />
<body>
</body>
</html>

The full code auth.php file

<?php
    $user;
    $pass;
    if (isset($_POST['user']))  $user = $_POST['user'];
    else
    {
        echo 'err_u_Username is not specified';
        exit();     
    }
    if (isset($_POST['pass']))  $pass = $_POST['pass'];
    else
    {
        echo 'err_p_Password is not specified';
        exit();
    }
    if ($user = 'defuser' && $pass = '123456') echo ('That\'s right!');
    else echo ('That\'s not right!');
?>

This can easily be solved by including the code in the same file as the document. But I wish to call the function from a different file and then return it to the file that has foo() or the document. Simply, I want the AJAX function to return the responseText without it giving an `undefined' every time. If this has anything to do with synchronization: I want to know of any workarounds against this problem.

Share Improve this question edited Apr 23, 2012 at 11:01 Samik Sengupta asked Apr 23, 2012 at 10:55 Samik SenguptaSamik Sengupta 1,9739 gold badges32 silver badges51 bronze badges 2
  • It's not good practice to tell how people should react to your question... – Jasper Commented Apr 23, 2012 at 10:58
  • Just put the value returning in an hidden field and call another function after this and grab the value from that hidden field. – Ravinder Singh Commented Apr 23, 2012 at 11:01
Add a ment  | 

2 Answers 2

Reset to default 2

The gist of it has already been mentioned, but I would like to go into a bit more depth as to why this doesn't work.

You have the following code:

request.onreadystatechange = function() 
{
    if (request.readyState == 4)
    {
        document.write(request.responseText);
        return(request.responseText);
    }
}

Basically, you are setting the onreadystatechange event to the value of an anonymous function. In that anonymous function, you are returning a value, which won't be returned to the caller of ajax_phprequest(), but to the caller of the anonymous function, which is the event system and which doesn't care much about what value is returned.

This happens this way because it all happens asynchronously. In other words, you call ajax_phprequest() and all that happens at that moment happens behind the screens. The user can continue working like nothing has happened. However, in the background, the php file is requested and hopefully returned. When that happens, you get to use the contents, but the moment at which you called ajax_phprequest() has long since passed.

A proper way would be to use a callback function instead. It could look something like this:

function ajax_phprequest(data, php_file, callback)
{
    var request =  createXMLHttp();
    request.open("POST", php_file, true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(data);
    request.onreadystatechange = function() 
    {
        if (request.readyState == 4)
        {
            document.write(request.responseText);
            callback(request.responseText);
        }
    }
}

function foo()
{
    ajax_phprequest("user=defuser&pass=123456","auth.php", function (text)
    {
        alert(text);
    });
}

That is because the call is ASYNCHRONOUS so you cannot return from stack the usual way, i.e. your alert(ajax_phprequest("user=defuser&pass=123456","auth.php")); is evaluated before the ajax response is returned ... you need to use a callback:

function callback( text ){
    // something
}

...
if (request.readyState == 4){
    callback( request.responseText );
}
发布评论

评论列表(0)

  1. 暂无评论