1

I am trying to send variable to php using javascript and trying to receive back and alert that variable. But $_POST['data'] doesn't get a data that I pass and $obj is always null.

If I just echo "some text"; it alerts that.

Here is my javascript code:

getMessageType('some data'); //function call

function getMessageType(str)
{
    data = {'key': str};
    var xhr = new XMLHttpRequest();
    var url = "test.php";
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    console.log(data); //Object {key: "some data"}
    xhr.send(data);

    xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
          console.log(xhr.responseText);
        }
    };
}

Here is my PHP code:

<?php       
$obj = $_POST['key'];
echo $obj;

What I am doing wrong ?

Any help is appreciated. Thanks

14
  • it's a string some data which I am passing when I call getMessageType function. you can see at top of code. Commented Jul 19, 2017 at 14:14
  • You're not providing any sort of key called data, so there's no way to retrieve the value by that key if you never set that key. Perhaps the string is in the POST body instead of the key/value pairs? Commented Jul 19, 2017 at 14:15
  • I still get blank alert even after setting the key. Commented Jul 19, 2017 at 14:27
  • 1
    Please, quit using alert() for troubleshooting., use console.log() instead. Commented Jul 19, 2017 at 14:31
  • 1
    That's your problem. Add console.log(data); just before the send to make sure it is populated. Commented Jul 19, 2017 at 14:52

2 Answers 2

1

You are posting the data with the content-type application/x-www-form-urlencoded.

Therefore your data must be form encoded :

data = "key="+str;

You can check this in your browser if the POST info has any "form data"

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

Comments

0

If you need to pass JSON data (object) having content-type application/x-www-form-urlencoded you need to convert it in text format:

  var params = "";
    for (key in data) {
        params += encodeURIComponent(key)+"="+encodeURIComponent(data[key])+"&";
    }

and then send it

xhr.send(params);

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.