Search code examples
javascriptphpjsonpostxmlhttprequest

send and receive get and post json request to php with javascript's XMLHttpRequest


I want to make some simple client server model with php and javascript with json data.

  • here, after request $_POST is empty array, But I send params with POST request.
  • JSON.parse is getting error where I received json data from php as JSON.parse(this.responsetText)

so, any suggestion for me where I do a mistake?

html form

<form onsubmit="submitform(event)">
        <fieldset>
          <legend>registration</legend>

          <label for="username">username:</label>
          <input
            type="text"
            name="username"
            value="xyz"
            id="usernmae"
            required
          />
          <br />
          <label for="password">password:</label>
          <input
            type="password"
            name="password"
            value="123"
            id="password"
            required
          />
          <br />
          <label for="name">name:</label>
          <input type="text" name="name" value="xyz" id="name" required />
          <br />
          <label for="city">city:</label>
          <select name="city" id="city" required>
            <option value="city1" selected>city1</option>
            <option value="city2">city2</option>
            <option value="city3">city3</option></select
          ><br />
          <label for="company">company:</label>
          <input type="text" name="company" value="abc" id="company" required />
          <br />
          <input type="reset" name="reset" value="reset" />
          <input type="submit" name="submit" value="submit" />
        </fieldset>
      </form>

this is my script

<script>
      function $(x) {
        return document.getElementById(x);
      }
      function submitform(event) {
        event.preventDefault();
        const xhr = new XMLHttpRequest();

        xhr.onprogress = function () {
          console.log("on progress");
        };

        xhr.onload = function () {
          if (parseInt(this.status / 100) === 2) {
            console.log(this.responseText);
          } else {
            console.log("some error occur");
          }
        };

        params = `
        {
          "username": "${$("usernmae").value}",
          "password": "${$("password").value}",
          "name": "${$("name").value}",
          "city": "${$("city").value}",
          "company": "${$("company").value}"
        }`;

        console.log(params, typeof params);
        xhr.open("POST", "http://localhost/learnphp/test.php", true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.send(params);
      }
</script>

php file

<?php 
    print_r($_POST);
    $arr = [];
    $arr[sizeof($arr)] = $_POST;    

    header("Content-Type: application/json");
    echo json_encode($arr[sizeof($arr) - 1]);
?>

current output is ...

enter image description here


Solution

  • I got an answer from this question

    instead taking a direct $_POST I need to change it with $_POST = json_decode(file_get_contents('php://input'), true);

    and it is working for me.