Search code examples
javascriptphpajaxhidden-field

Get hidden field value from javascript after php function


I have some troubles with my code. I have a Javascript function inside my page and a PHP function that fills a hidden field. When I read the hidden field from Javascript, the value read is not the current one. It seems like there is no refresh. I need help, please. Every hint really appreciated! Thanks!

Here's my Javascript code:

var username = document.getElementById('user').value;
checkUserName(username);

var opennextpage = document.getElementById('hidden_field_openpage').value;

if (opennextpage == 'YES'){
// open next page
}
else{
alert('Can't open page');
}

I call the PHP page via AJAX is this way:

function checkUserName(username){
    var strURL  = "js/ax_checkusername.php?user="+ username; 
    var req = getXMLHTTP();

    if (req)
    {
        req.onreadystatechange = function()
        {
            if (req.readyState == 4)
            {
                // only if "OK"
                if (req.status == 200)
                {
                    document.getElementById('hidden_field_openpage').value = req.responseText;
                } 
                else 
                {
                    alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                }
            }
        }
    }
    req.open("GET", strURL, true);
    req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.send(null);
}

Solution

  • Why don't you combine both, like this:

    function checkUserName(username){
        var strURL  = "js/ax_checkusername.php?user="+ username; 
        var req = getXMLHTTP();
    
        if (req)
        {
            req.onreadystatechange = function()
            {
                if (req.readyState == 4)
                {
                    // only if "OK"
                    if (req.status == 200)
                    {
                       if (req.responseText == 'YES'){
    // open next page here itself
    }
    else{
    alert('Can\'t open page');
    };
                    } 
                    else 
                    {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }
            }
        }
        req.open("GET", strURL, true);
        req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
        req.send(null);
    }
    

    and then just call checkUserName(username) ?