javascript – Posting js variables to PHP not running in any method-ThrowExceptions

Exception or error:

In my JS code, I take in 3 inputs on a html page and save them to local storage. I then want to send these variables to php in order to save them to my database. No matter how hard I try no tutorial using ajax, jquery etc allows me to successfully post and echo variables from javascript in my php code. I see no reason why my code below doesn’t echo the variables, but it doesn’t.

Full code:

Exact PHP elements (just trying to send normal variables right now as it still won’t work”


foreach($_POST as $post_var){


const xhr = new XMLHttpRequest();
xhr.onload = function(){
    const serverResponse = document.getElementById("serverResponse");
    serverResponse.innerHTML = this.responseText
};"POST", "eDBase.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
How to solve:

If $post not work try using input php
$data = json_decode(file_get_contents(‘php://input’), true);


When calling my function with the inputs onclick=showFunction; I was passing nothing to the function. In order for my values to be echoed in php I had to pass a parameter to the function onclick=function(‘text or variable’); IDK how I missed that.


Try using the FormData()

 let form = new FormData();
 form.append('name', 'dominic');
 form.append('message', 'bumbaclaat');

 const xhr = new XMLHttpRequest();"POST", "eDBase.php");
 xhr.onreadystatechange = function(){

    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
       const serverResponse = document.getElementById("serverResponse");
       serverResponse.innerHTML = this.responseText;
    else console.log('error')


Comment out the setRequestHeader to test it.

And at PHP

  echo $_POST['name'];
  echo $_POST['message'];
 echo 'There was a problem';

Leave a Reply

Your email address will not be published. Required fields are marked *