Phob1a
Phob1a

Reputation: 773

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);
                }

            };

Upvotes: 0

Views: 144

Answers (3)

user2945107
user2945107

Reputation:

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);
    }
};

Upvotes: 0

Raydel Miranda
Raydel Miranda

Reputation: 14360

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.

Upvotes: 0

ComFreek
ComFreek

Reputation: 29424

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.

Upvotes: 1

Related Questions