javascript - 在 PHP 和 Ajax 中使用 Json 传递值

标签 javascript php arrays json ajax

我是 Json 的初学者。 HTML table 中包含一些值,需要使用 json 将这些值传递到 prescription.php 页面。我尝试过,但在 ajax 成功后,它在错误日志中显示一条错误消息:

e = {readyState:4,getResponseHeader:f,getAllResponseHeaders:f,setRequestHeader:f,overrideMimeType:f,...}

这是我的 HTML 代码段:

    <form method="post" id="prescriptionn" enctype="multipart/form-data">  
       <div class="table-responsive">
           <table class="table table-bordered mb-0" id="medical">
                <thead>
                    <tr>
                         <th>Medicine Name</th>
                         <th>Morning</th>
                         <th>Noon</th>
                         <th>Night</th>
                         <th> <button type="button" name="add" id="add" 
                                class="btn btn-success btn-xs"> + </button>  </th>

                     </tr>
                 </thead>
                 <tbody id="rows"> 
                 </tbody>
            </table>
                        <br><br>
             <div align="center">
                <input type="hidden" value="<?php echo $row['apt_id'] ?>" 
                          id="getapt" name="getapt" class="btn btn-primary">

                 <input type="hidden" value="<?php echo $row['p_id'] ?>" 
                          id="getpid" name="getpid" class="btn btn-primary">


                  <input type="button" name="submit" 
                           id="submit" class="btn btn-primary" value="Enter Prescription">

             </div>
            </div>
          </form>

这是我的 ajax 调用

<script>
$(document).ready(function(){

var count=0;
$(document).on('click','#add',function() {
    count++; 

    var html= '';
    html += '<tr>';

    html += '<td id="medicinename"> <select  name="med_name[]" id="med_name[]" class="form-control med_name" ><option value=""> Select Medicine</option> <?php echo fill_select_box($conn, "0");  ?></select></td>';
    html += '<td id="mor"> <input type="text" name="morning[]" id="morning[]" class="form-control morning" /> </td>';
    html += '<td id="noo"> <input type="text" name="noon[]" id="noon[]" class="form-control noon" /> </td>';
    html += '<td id="nigh"> <input type="text" name="night[]" id="night[]" class="form-control night" /> </td>';
   // html += '<td class="charge"> </td>';
    html += '<td> <button type="button" name="remove" id="remove" class="btn btn-danger btn-xs remove" >  -  </button> </td>';
    html +=  '</tr>';

    $('#rows').append(html);

});
        });
</script>

 <script>

$(document).ready(function () {
$(document).on('click', '#submit', function () {

    var getapt = $('#getapt').val();  
    var getpid = $('#getpid').val();  

       var ids={ 
            'getapt': getapt,
             'getpid': getpid,
                }

        var modess = $('#rows tr').map(function() {
        let $tr = $(this);

        return [ { 
               "medname": $(this).find('.med_name').val(),
               "morning":$(this).find('.morning').val(),
               "noon":$(this).find('.noon').val(),
               "night": $(this).find('.night').val(),
                 } ]

                 console.log(modess);
                       });

   var ids = JSON.stringify(ids);
   var medical = JSON.stringify(modess);

          $.ajax({
              url: "adminquery/prescription.php", // Url to which the request is send
              method: "POST",             // Type of request to be send, called as method
              data:{
                   index1: medical, 
                   index2: ids
              },
              dataType:'json',             
              cache: false,
              success: function(data){
                alert('Items added');
            },
            error: function(e){
                console.log(e);
            }

          })

});

});
</script>

这是prescription.php页面中的php代码

<?php

session_start();
require_once "../auth/dbconnection.php";

// if (isset(json_decode($_POST["data"])) {

  $jsondata = json_decode($_POST["index1"]);
  $jsondata1 = json_decode($_POST["index2"]);

  echo $id= $jsondata1->getpid;
  echo $apt= $jsondata1->getapt;

    if($stmt = mysqli_prepare($conn,"INSERT INTO prescription (apt_id,user_id,p_id, med_records,date) VALUES (?, ?, ?, ?, ?)")){

      $cur_date = date('Y-m-d H:i:s');

        $user_id= $_SESSION['user_id'];
        // $p_id= $_POST['getpid'];
        // $apt_id= $_POST['getapt'];

        mysqli_stmt_bind_param($stmt, "sssss",$apt,$user_id, $id,$jsondata,$cur_date);

       echo "Records inserted successfully.";

} else{

  echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);

}

  mysqli_stmt_close($stmt);

?>

我不知道我哪里错了。非常感谢任何帮助。

最佳答案

根据我在 PHP 代码中看到的内容,我知道您想要存储 JSON index1 的文本,因为它直接位于 med_records sql 元素下,并且您想要当您尝试解码它并提取两个值时发送 PARSE AS AN OBJECT index2:

  $jsondata1 = json_decode($_POST["index2"]);

  echo $id= $jsondata1->getpid;
  echo $apt= $jsondata1->getapt;

因此,您应该只解码其中的一个,并将第二个保留为字符串:

$jsondata = $_POST["index1"];

as $jsondata 您想将其作为 json 字符串存储在数据库中,对吧?如果不是,请提供一些有关预期数据(表格架构)的信息。

请务必知道您的代码不是很安全:首先,它应该验证是否发送了正确的值(解码解析的数据,检查预期的 key ,再次编码),还应该为以下情况做好准备: session 中不再有用户 ID。

关于javascript - 在 PHP 和 Ajax 中使用 Json 传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59700802/

相关文章:

javascript - 如何合并对象属性并让其合并并在一个对象下

javascript - Javascript(Ionic)中两个移动设备之间的距离

php - 如何在 PHP 中回显 mysql CURRENT_DATE()?

javascript - Google 脚本自定义函数 - 范围数组作为参数

java - 打印数组、设置数组

javascript - 修改 Highcharts 中的X轴

javascript - onclick需要双击

javascript - 我应该如何组织一个对象以尽可能地保持一切分离?

PHP require_once 没有得到一个变量

javascript - 当新数据插入 mysql 时,ajax 通知警报弹出或发出声音