2

My data is not inserting into database, I get a blank response from the console log and network. I'm kinda lost my javascript source code is mix with other stack overflow answers as well as my PHP code.

<form id="requestForm">
    <input type="text" name="fName" id="name">
    <input type="text" name="fAddress" id="address">
    <input type="text" name="fComment" id="comment">

    <input type="submit" value="Submit" name="nameSubmit">
</form>

<script>
        document.querySelector('#requestForm').addEventListener('submit', postRequest);

        function postRequest(e){
            e.preventDefault();

            const params = {

                fName: document.querySelector('#name').value,
                fAddress: document.querySelector('#address').value,
                fComment: document.querySelector('#comment').value,

            };
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'addRequest.php', true);
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.onload = function(){
                console.log(this.responseText);
            }
            xhr.send(params);
        } 
    </script>
</body>

Here's the PHP code:

require_once 'Database.php';

var_dump($_POST); // returns `array(0) {}`

    if (isset($_POST['nameSubmit'])) {
var_dump($_POST); // shows no response    
        $r = $_POST['fName'];
        $o = $_POST['fAddress'];
        $p = $_POST['fComment'];

        $query = "INSERT INTO user_request(name, address, comment) VALUES(?,?,?)";
        $stmt = $db->prepare($query);
        $insert = $stmt->execute([$r, $o, $p]);

        if($insert){
            echo 'Success';
        }else{
            echo 'Error';
        }
    }
thisisnotwakanda
  • 75
  • 1
  • 2
  • 6
  • You need to call `prepare()` first – Rotimi Oct 04 '18 at 12:24
  • 3
    I think `$_POST['nameSubmit']` is not defined, because you don't send it to the server, and therefore the code inside the if statement never gets executed. What does `var_dump($_POST)` return? – T K Oct 04 '18 at 12:25
  • Could this be a problem having the params as `const` ? – Cid Oct 04 '18 at 12:25
  • 1
    You should open the browser debugger, network panel and check what happen: check if parameters are passed to the php page and check the resulto the php page – kiks73 Oct 04 '18 at 12:25
  • No defining params as const isn't the issue. The issue is as TK says there isn't a variable `nameSubmit` being passed to the server. More than likely the php code was taken from a form submit example where the submit button had name "nameSubmit". – scrappedcola Oct 04 '18 at 12:27
  • `var_dump($_POST)` returns `array(0) {}` – thisisnotwakanda Oct 04 '18 at 12:29
  • Where did you put that line? Edit your question with what you have tried and the output of a `var_dump()` you can write as a comment in your code. – MrUpsidown Oct 04 '18 at 12:31
  • I put it before the `if(isset)` line.. and when I put it after the `if(isset)` it does not show any response. Edit: edit my answer in PHP part – thisisnotwakanda Oct 04 '18 at 12:36

2 Answers2

3

I believe the post parameter nameSubmit does not exsist.
Use the var_dump() function for dump all $_POST
From my prespective, the only parameter given was

  • fName
  • fAddress
  • fComment

Why not check for request method instead?
This is better than checking if a variable exsisted or not. You can do the checks for required parameter later after you're sure this is a POST request.

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    // Do whatever you want when POST request came in
}

UPDATE :
Here is the answer you wanted!

<form id="requestForm">
    <input type="text" name="fName" id="name">
    <input type="text" name="fAddress" id="address">
    <input type="text" name="fComment" id="comment">

    <button onclick="sendData();" type="button">Submit</button>
</form>

<div id="testdiv"></div>

    <script>

      function sendData(){
          var data = new FormData();
          data.append('fName', document.getElementById("name").value);
          data.append('fAddress', document.getElementById("address").value);
          data.append('fComment', document.getElementById("comment").value);

          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'test.php', true);
          xhr.onload = function () {
            if(xhr.status !== 200){
              // Server does not return HTTP 200 (OK) response.
              // Whatever you wanted to do when server responded with another code than 200 (OK)
              return; // return is important because the code below is NOT executed if the response is other than HTTP 200 (OK)
            }
            // Whatever you wanted to do when server responded with HTTP 200 (OK)
            // I've added a DIV with id of testdiv to show the result there
            document.getElementById("testdiv").innerHTML = this.responseText;
          };
          xhr.send(data);
      }

    </script>
</body>

The PHP code :

<?php

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    var_dump($_POST);
}else{
    header('HTTP/1.0 403 Forbidden');
}

?>

To add another field, add another data.append function below data var.
The submit button MUST BE CLICKED. To allow the use of enter, add an event listener for it!.
What it looks like on my end : https://image.ibb.co/gfSHZK/image.png
Hope this is the answer you wanted.

PlanetCloud
  • 314
  • 2
  • 11
  • Asking for clarification : Why is this down voted? – PlanetCloud Oct 04 '18 at 12:34
  • I get an error in PHP saying `Undefined index: fName` and `Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null in C:\xampp\htdocs` and another `C:\xampp\htdocs\: PDOStatement->execute(Array)` – thisisnotwakanda Oct 04 '18 at 12:43
  • Hi, Have you tried to do a `var_dump()` on `$_POST` as I mentioned above? – PlanetCloud Oct 05 '18 at 04:59
  • @thisisnotwakanda, sorry for my previous response. I've tested your code with var_dump and it returns an empty array... Please check my updated answer as this is definitely what you're looking for. (Tested on localhost with PHP 7.1). – PlanetCloud Oct 05 '18 at 05:23
  • @thisisnotwakanda Asking for clarification : Is this issue resolved? – PlanetCloud Oct 05 '18 at 13:40
  • @thisisnotwakanda Glad to hear that :), please upvote the answers back, thank you. – PlanetCloud Oct 07 '18 at 12:27
2

Two issues:

1.) Params not sent properly/at all because lack of serialization. When you use form content-type your params object need to be in a particular format name=value&name2=value2. So to facilitate that you need to transform your ojbect using something like:

function getReadyToSend(object) {
    var objList = [];
    for (var prop in object) {
        if (object.hasOwnProperty(prop)) {
            objList.push(encodeURI(prop + '=' + object[prop]));
        }
    }
    return objList.join("&");
}

So your sending becomes: xhr.send(getReadyToSend(params));

2) Your php is expecting the submit button to be sent. if (isset($_POST['nameSubmit'])) { You don't have a variable being sent called nameSubmit you can fix this by either including it or check that each variable is set instead. I would suggest the latter that way you can error handle should 1 or more are not passed.

Suggestion: Update your onload to check status:

if (xhr.status === 200)
{
    console.log(xhr.responseText);
}
else if(xhr.status !== 200)
{
    console.log('Request failed.  Returned status of ', xhr.status);
}

Example fiddle: http://jsfiddle.net/qofrhemp/1/, open network tab and inspect the call you will now see the params in form data for the call that fires when submit clicked.

scrappedcola
  • 10,423
  • 1
  • 32
  • 43
  • Didn't I include the `nameSubmit` when i put it like this? ``. Thank you for your input sir, your solution seems advanced for me, but for now I'll accept @PlanetCloud's answer and I'll definitely try your solution later. – thisisnotwakanda Oct 06 '18 at 15:15
  • You are doing an ajax call not a form submit. It's not in your params list that you explicitly send to the server. – scrappedcola Oct 06 '18 at 22:35