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: https://codeshare.io/ayvK9e

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

PHP:

foreach($_POST as $post_var){
echo($post_var);
}

JS:

const xhr = new XMLHttpRequest();
xhr.onload = function(){
    const serverResponse = document.getElementById("serverResponse");
    serverResponse.innerHTML = this.responseText
};

xhr.open("POST", "eDBase.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=dominic&message=bumbaclaat");
How to solve:

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

Answer:

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.

Answer:

Try using the FormData()

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

 const xhr = new XMLHttpRequest();

 xhr.open("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')
 };

 xhr.send(form);

Comment out the setRequestHeader to test it.

And at PHP

if(isset($_POST['name'])){
  echo $_POST['name'];
  echo $_POST['message'];
}
else{
 echo 'There was a problem';
}

Leave a Reply

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