簡體   English   中英

通過 Ajax 調用使用 JSON 傳遞值

[英]Pass values using JSON via Ajax Call

我是JSON初學者。 在我的 Web 應用程序中,我嘗試將table值轉換為JSON並使用ajax call傳遞到另一個頁面。

下面是我的ajax query ,我嘗試將其轉換為table values並傳遞給prescription.php頁面以保存記錄。 有兩個不同的獨立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>

這是我的 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);
?>

這是我的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>

但是當我提交按鈕時什么也沒有發生。 請給我一些改進我的代碼的建議可能會受到高度贊賞。

以下方法展示了如何使用 jQuery Ajax 發送 HTML 表格數據並保存在數據庫中。 希望這會有所幫助。

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>

一旦通過 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