0

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

            };
2
  • 2
    When using Ajax, it is advised to use a Javascript library like Dojo or jQuery to do the heavy lifting. Commented Nov 1, 2013 at 13:08
  • 1
    Right now, there are several things that could be going wrong. To narrow down the issue, I'd recommend changing your PHP page to just print the string, nothing else. ie: <?php print 'test message'; ?> Commented Nov 1, 2013 at 13:12

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

The problem is that even if I do this, the alert appears empty, not with the String I declared in the PHP
@Phob1a What is the response code? Have you tried user2945107' suggestion to assign the event handler before you calling open() and send()?
I did follow the suggestion. What do you mean the response code? The alert just prints an empty String.
@Phob1a Which alert()? Did you insert my code into yours? It should log two times in the developer console.
This is what was printed in the console: Refused to set unsafe header "Content-length" index.html:58 Refused to set unsafe header "Connection" index.html:59 Uncaught TypeError: Cannot call method 'alert' of undefined demophonegap.js:39 XMLHttpRequest cannot load http://------.php. Origin null is not allowed by Access-Control-Allow-Origin. index.html:1 AJAX finished, got 0 status code index.html:51 Response text is:
|
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.