简体   繁体   中英

Accessing all the items of JSON array of nested objects using PHP's for-each loop

I have built a form in HTML and send all the data entered by the user using JSON.stringify() and XMLHttpRequest() to a PHP file and stored that in a variable. Now I want to display all that information on a web page, for which I want to use for-each loop, but i am not understanding how exactly should i pass the parameters in the loop and access them.

Here is the HTML code:-

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="styling.css">
</head>
<body>
    <div class="container">
        <h1>Popup for adding/editing Expertise details</h1>
        <a href="#" class="button">Add/Edit</a>
    </div>

    <div class="popup">
        <div class="popup-content">

            <div class = "register">
      <form method="post" id="register" action="">

          <label for="area"> Expertise Area: </label><br>
          <input type="text" name="area" id="area"
          placeholder="Enter your Expertise Area"><br><br>
          <label> Experience: </label><br>
          <label for="mnth">No. of months:</label>
          <input type="number" id="mnth" name="mnth" min="1" max="11">
          <label for="yr">No. of years:</label>
          <input type="number" id="yr" name="yr" min="1" max="50"><br><br>
          <label> Rates </label><br><br>
          <label for="remote"> Remote: </label><br>
          <select id="remote_option">
            <option>per hour</option>
            <option>per topic</option>
            <option>per chapter</option>
          </select>
          <label for="remote_amt">Amount in Rs.:</label>
          <input type="number" id="remote_amt" name="remote_amt">
          <label for="center"> Center: </label><br>
          <select id="center_option">
            <option>per week</option>option>
            <option>per month</option>option>
          </select>
          <label for="center_amt">Amount in Rs.:</label>
          <input type="number" id="center_amt" name="center_amt">
          <label for="learner"> Learner's Place: </label><br>
          <select id="learner_option">
            <option>per class</option>option>
            <option>per hour</option>option>
          </select>
          <label for="learner_amt">Amount in Rs.:</label>
          <input type="number" id="learner_amt" name="learner_amt"><br>
          <label for="my"> My Place: </label><br>
          <select id="my_option">
            <option>per class</option>option>
            <option>per hour</option>option>
          </select>

          <label for="my_amt">Amount in Rs.:</label>
          <input type="number" id="my_amt" name="my_amt"><br><br>
          <div class="button">
            <button id="btn">Submit</button>
          </div>
          <img src="close.png" class="close" alt="Close">
      </form>
      </div>

        </div>
    </div>
  <script>
    document.querySelector(".button").addEventListener("click", function(){
       document.querySelector(".popup").style.display = "flex";});
  document.querySelector(".close").addEventListener("click", function(){
       document.querySelector(".popup").style.display="none";});
  </script>

  <script>
    let data=[];
    const addData=(ev)=>{
      ev.preventDefault();
      let d={
        exp_area: document.getElementById('area').value,
        exp_yrs: document.getElementById('mnth').value,
        exp_mnth: document.getElementById('yr').value,
        rates: [
          {
            mode: 'remote',
            charge: document.getElementById('remote_amt').value,
            unit: document.getElementById('remote_option').value
          },
          {
            mode: 'center',
            charge: document.getElementById('center_amt').value,
            unit: document.getElementById('center_option').value
          },
          {
            mode: 'learner',
            charge: document.getElementById('learner_amt').value,
            unit: document.getElementById('learner_option').value
          },
          {
            mode: 'my',
            charge: document.getElementById('my_amt').value,
            unit: document.getElementById('my_option').value
          }
        ]
      }
      data.push(d);
      document.forms[0].reset();

      const JsonString = JSON.stringify(data);
      console.log(JsonString);

      const xhr = new XMLHttpRequest();

      xhr.open("POST","receive.php");
      xhr.setRequestHeader("Content-Type","application/json");
      xhr.send(JsonString);
    }

    document.addEventListener('DOMContentLoaded',()=>{
      document.getElementById('btn').addEventListener('click',addData);
    });
  </script>
  <script type="text/javascript" src="submit.js"></script>
</body>
</html>

And here is the JSON object which is sent as Request PayLoad, as I can see in the network tab in developers tool:-

[{"exp_area":"gfds","exp_yrs":"","exp_mnth":"","rates":[{"mode":"remote","charge":"","unit":"per hour"},{"mode":"center","charge":"","unit":"per week"},{"mode":"learner","charge":"","unit":"per class"},{"mode":"my","charge":"","unit":"per class"}]}]

this is what i am trying in my PHP file:-

<?php

$reuestPayload = file_get_contents("php://input");
$arr = json_decode($reuestPayload,true);
var_dump($arr);

$output= "<ul>";
foreach ($arr[d] as $value) {
    $output .= "<h4>".$d['exp_area']."</h4>";
    $output .= "<h4>".$d['exp_yrs']."</h4>";
    $output .= "<h4>".$d['exp_mnth']."</h4>";
    $output .= "<h4>".$d['rates']['mode']."</h4>";
    $output .= "<h4>".$d['rates']['charge']."</h4>";
    $output .= "<h4>".$d['rates']['unit']."</h4>";

}
$output.="</div>";
?>

Request payload:

这是请求有效负载屏幕截图

As the data is being sent and received asynchronously the page will not be refreshed after an execution of the submit routine. What you might do is return HTML from your backend and add this to a specific element as part of the XHR response.

Add a result element to show the server response:

<div id="result"><h3>Result:</h3></div> 

Modify your JS routine:

Add this before your xhr.open() lines:

xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        document.getElementById('result').innerHTML += (xhr.responseText);
    }
}

Some remarks regarding your code:

  1. You start your PHP response with $output= "<ul>"; but end with $output.="</div>"; -> change the <ul> to <div> .
  2. As pointed out by aXuser26 your server-side code is errornous, the [d] should be removed. I think you got confused as you labelled your JSON variable "d" on the client-side but the variable name won't be passed to the server.
  3. There is a "q" missing in your variable $reuestPayload (although this won't be a problem^^).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM