简体   繁体   中英

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.

Javascript fragment:

var params = "action=getAlbums";
            var request = new XMLHttpRequest();

            request.open("POST", PHP CODE URL, true);
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.setRequestHeader("Content-length", params.length);
            request.setRequestHeader("Connection", "close");
            request.send(params);

            request.onreadystatechange = function() {

                   var phpmessage = request.responseText;
                   alert(phpmessage);

            };

PHP fragment:

$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];

// Go to a function depending the action required
switch ($deviceFunction)
{
    case "getAlbums":
        getAlbumsFromDB();
        break;
}



function getAlbumsFromDB()
{

    echo "test message!";

}

The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:

request.onreadystatechange = function() {
                if(request.status == 200) {
                    var phpmessage = request.responseText;
                   alert(phpmessage);
                }

            };

The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState

Rewrite your JS:

request.onreadystatechange = function () {
  if (request.readyState == 4) {
    console.log('AJAX finished, got ' + request.status + ' status code');
    console.log('Response text is: ' + request.responseText);
  }
}

In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.

I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.

I faced a similar problem working with Django. What I did: I used a template language to generate the javascript variables I needed.

I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.

<?php
    <script type="text/javascript" ... >
          SOME_VARIABLE = "{0}".format(php_function())  // php_function resolve the value you need
   </script>
?>

The I use SOME_VARIABLE in my scripts.

Please specify your onreadystatechange event handler before calling open and send methods. You also should make your choice between GET and POST method for your request.

If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :

request.onreadystatechange = function() {
    if (request.readyState==4 && request.status==200) {
        var phpMessage = request.responseText;
        alert(phpMessage);
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM