0

I've been at this for hours and have yet to find a solution. Chrome's network activity shows that the post is being sent and the payload is "id=a1" but the php always returns an empty string. Either this is some silly typo that I've missed for the longest time, or my server host php.ini is blocking it. I contemplated the later, but I've used plenty of post scripts previously on this host without issue.

I've tried every combination I could think of with no avail :(

What could be causing this?

relevant .js:

var xhr;
if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.open("POST", "api.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www/form-urlencoded");
xhr.send("id=" + "a1");
xhr.onreadystatechange = display_data;

function display_data() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    alert(xhr.responseText);
  }

}

relevant .php:

$id = $_POST['id'];
echo $id;

4
  • Make xhr.send("id=" + "a1"); your last line of code and try again Commented Jan 3, 2016 at 5:00
  • This change gives me the same result :\ Commented Jan 3, 2016 at 5:07
  • You made a typo in the request header string. You had application/x-www/form-urlencoded, you need application/x-www-form-urlencoded. Making this change alters the output from an error message mentioning an undefined index, 'id', to a1 Commented Jan 3, 2016 at 5:17
  • Interesting, glad you found the solution! Commented Jan 3, 2016 at 5:24

1 Answer 1

1

Try this...

Edited. Missed a semicolon.

var xhr;
if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.open("POST", "api.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("id=" + "a1");
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    alert(xhr.responseText);
  }

};

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

1 Comment

You don't need semi-colons after the end of a block. You've merely placed one after the closing brace for the handler for the onreadystatechange event. The error message remains the same as the one generated by the code in the question. ;) - The only reason your code now works, is that you've altered the request-header string in an edit.

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.