最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Send PHP POST using Javascript AJAX - Stack Overflow

programmeradmin1浏览0评论

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="ment">

    <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('#ment').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, ment) VALUES(?,?,?)";
        $stmt = $db->prepare($query);
        $insert = $stmt->execute([$r, $o, $p]);

        if($insert){
            echo 'Success';
        }else{
            echo 'Error';
        }
    }

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="ment">

    <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('#ment').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, ment) VALUES(?,?,?)";
        $stmt = $db->prepare($query);
        $insert = $stmt->execute([$r, $o, $p]);

        if($insert){
            echo 'Success';
        }else{
            echo 'Error';
        }
    }
Share Improve this question edited Oct 4, 2018 at 12:38 thisisnotwakanda asked Oct 4, 2018 at 12:21 thisisnotwakandathisisnotwakanda 751 gold badge2 silver badges6 bronze badges 8
  • You need to call prepare() first – Rotimi Commented Oct 4, 2018 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 Commented Oct 4, 2018 at 12:25
  • Could this be a problem having the params as const ? – Cid Commented Oct 4, 2018 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 Commented Oct 4, 2018 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 Commented Oct 4, 2018 at 12:27
 |  Show 3 more ments

2 Answers 2

Reset to default 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="ment">

    <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("ment").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.

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 bees: 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/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.

发布评论

评论列表(0)

  1. 暂无评论