简体   繁体   中英

Pass values using JSON via Ajax Call

I am beginner on JSON . In my web application I am trying convert the table values into JSON and pass to another page using 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. There are two different separate java script variables which need to sent to the above page.

<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

<?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.

    <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. 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

<?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 */
}

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