0

I am beginner of Json. There are some values contains in the HTML table, need to pass those values using json to prescription.php page. I tried, but after ajax success it shows a error message in error log:

e = {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

Here is my HTML code segments:

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

Here is my ajax call

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

Here is the php codes in prescription.php page

<?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);

?>

I don't know where I went wrong. Any help is highly appreciated.

3
  • Remove dataType: 'JSON' Commented Jan 12, 2020 at 4:29
  • @RiteshKhandekar I removed, after ajax success it shows Records inserted successfully, when I see the database isn't save. There were no record inserted ????? Commented Jan 12, 2020 at 4:38
  • 1
    mysqli_stmt_execute($stmt); Commented Jan 12, 2020 at 4:50

1 Answer 1

1

Based on what I see in your PHP code I understand that you want to store the TEXT of a JSON index1 as it goes directly under med_records sql element and you want to send PARSE AS AN OBJECT index2 as you try to decode it and extract two values:

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

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

Therefore you should decode only on of those and keep the second as string:

$jsondata = $_POST["index1"];

as $jsondata you want to store just as json string in the database, right? If no then please provide some info about expected data (schema of the table).

Be sure to know that your code is not very safe: first of all it should verify if correct values were even sent (decode parsed data, check for expected keys, encode again), also should be prepared for a case when there is no user id in session anymore.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. It works. ;-) . Here when I retrieve this data from database, how can I separate these data and shows in separate column in HTML table
I strongly suggest execution of $.makeArray(modess); before you actually store it to avoid jQuery attributes like length or prevObject being sent too into your database. Then, having data from the database - for example each record in variable $row you can simply use json_decode foreach: $medRecords = json_decode($row['med_records']); and later: foreach($medRecords as $key => $object) { echo <td>'. $object->morning .'</td> };` etc.
Is before I sent to prescription.php page.
What do you mean? The dataType: 'JSON' or something else? This setting is not required as actually you encapsulate your jsons as string and send them using standard post format.
No I mean, $.makeArray(modess);. How to achieve this? How to send these values?? without var medical = JSON.stringify(modess);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.