简体   繁体   English

通过 Ajax 调用使用 JSON 传递值

[英]Pass values using JSON via Ajax Call

I am beginner on JSON .我是JSON初学者。 In my web application I am trying convert the table values into JSON and pass to another page using ajax call .在我的 Web 应用程序中,我尝试将table值转换为JSON并使用ajax call传递到另一个页面。

Below is my ajax query which I tried to convert the table values and pass to prescription.php page to save the records.下面是我的ajax query ,我尝试将其转换为table values并传递给prescription.php页面以保存记录。 There are two different separate java script variables which need to sent to the above page.有两个不同的独立java script variables需要发送到上述页面。

<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
            type: "POST",             // Type of request to be send, called as method
            data:{
                index1: medical, 
                index2: ids
            },
            dataType:'json',             
            cache: false,
            contentType: false,
            processData: false,
            async: false,
            //contentType: "application/json; charset=utf-8",
        })
    });
});
</script>

Here is my prescription.php page这是我的 recipe.php 页面

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

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

if($stmt = mysqli_prepare($conn,"INSERT INTO prescription (apt_id,user_id,p_id, med_records,date) VALUES (?, ?, ?, ?, ?)")){
    $user_id = $_SESSION['user_id'];
    mysqli_stmt_bind_param($stmt, "sssss", $user_id);
    echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);
}
// }else{
//     echo "now records";
// }

mysqli_stmt_close($stmt);
?>

Here is my HTML codes.这是我的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>

But nothing happen when I submit the button.但是当我提交按钮时什么也没有发生。 Please give me some suggestions to improve my code may highly appreciated.请给我一些改进我的代码的建议可能会受到高度赞赏。

Following Method show how to send HTML table data using jQuery Ajax and save in Database.以下方法展示了如何使用 jQuery Ajax 发送 HTML 表格数据并保存在数据库中。 Hope this will help.希望这会有所帮助。

function storeTblValuesSpecial(x)
{
var TableData = new Array();
$('#'+x+''+' tr').each(function(row, tr){
TableData[row]={

  "columOne" :$(tr).find('td:eq(1)').text()
, "columTwo" : $(tr).find('td:eq(2)').text()
, "columThree" : $(tr).find('td:eq(3)').text()

}    
}); 
TableData.shift();  // first row will be empty - so remove
return TableData;
}


function storeTblValuesAjax(y) {
var TableData;
TableData = JSON.stringify(storeTblValuesSpecial(y));
$.ajax({
type: "POST",
url: '../yourFile.php',
data: {
"pTableData" : TableData
},
success: function(msg){
alert('Success');
}
});
}

<table id="table1" class="table table-dark" border="1">
   <thead>
      <tr>
         <th scope="col">columOne</th>
         <th scope="col">columTwo</th>
         <th scope="col">columThree</th>
      </tr>
   </thead>
   <tbody>
      <tr>
      </tr>
   </tbody>
</table>

<button type="button" class="btn-danger" id = "delete" onclick="storeTblValuesAjax('table1')" >Save Table</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

From PHP File once the Post Request Sent through Ajax Call一旦通过 Ajax 调用发送 Post 请求,从 PHP 文件

<?php
session_start();

// Unescape the string values in the JSON array
$tableData = stripcslashes($_POST['pTableData']);

 // Decode the JSON array
$records = json_decode($tableData,TRUE);

$sizeOfArray =  sizeof($records);
for($test = 1; $test < $sizeOfArray; $test++)
{

$columOne= str_replace(",","",$records[$test]['columOne']);
$columTwo= str_replace(",","",$records[$test]['columTwo']);
$columThree= str_replace(",","",$records[$test]['columThree']);

/* From Here a general SQL Insert query , pass $columOne , $columTwo , $columThree as the insert values, the loop will continue until the entire table is saved */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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