0

I want to add medicine one time one row inserting if i want to add click button than open next medicine entry field than fillup and insert next row if one time 5 medicine entry than 5 time insert in to database .but here only one time insert data in to database checkbox is not working only accept first value

view page

enter image description here

i have need database

name      quantity     days     take medician
----------------------------------------------
Amit       1            2        morning,evening
-----------------------------------------------
Amitabh    2            3        evening,night
-----------------------------------------------
Amitabh    3            4        afternoon,night
kumar 
gupta

inserting curent database

name      quantity     days     take medician
----------------------------------------------
Amit       1            2        morning
-----------------------------------------------

html view page

 <tbody>
        <?php foreach ($app_booking as $row){ ?>
        <input type="hidden" name="doctorname" id="doctorname" value="<?php echo $row["doctor_name"];?>">
        <input type="hidden" id="doctorid" name="doctorid" value="<?php echo $row["doctor_id"];?>">
        <input type="hidden" id="appid"  name="appid" value="<?php echo $row["appointment_id"];?>">
        <input type="hidden" id="uid" name="uid" value="<?php echo $row["user_id"];?>">
    <?php };?>
        <tr>
        <td><input class="form-control" type="text" name="name" id="name" required=""></td>
        <td><input class="form-control" type="text" id="quantity" name="quantity" required=""></td>
        <td><input class="form-control" type="text" name="days" id="days"  required=""></td>
        <td>
            <div class="form-check form-check-inline">
             <label class="form-check-label">                                               
            <input class="form-check-input checkbox_value" type="checkbox" name="take_medicine[]" id="morning" value="Morning"> Morning
            </label>
        </div>
        <div class="form-check form-check-inline">
            <label class="form-check-label">
            <input class="form-check-input checkbox_value" type="checkbox" name="take_medicine[]" id="afternoon" value="Afternoon"> Afternoon
            </label>
            </div>
        <div class="form-check form-check-inline">
        <label class="form-check-label">
            <input class="form-check-input checkbox_value" type="checkbox" name="take_medicine[]" id="evening" value="Evening"> Evening
            </label>
        </div>
        <div class="form-check form-check-inline">
        <label class="form-check-label">
        <input class="form-check-input checkbox_value" type="checkbox" name="take_medicine[]" value="Night" id="night"> Night
        </label>
        </div>
        </td>
        <td>
        <a href="#"  name="add" id="btn1" value="Add" class="btn bg-success-light"><i class="fas fa-plus-circle"></i> Add Item</a>
        </td>
        <button type="button" onclick="save_medical_records();" class="btn btn-primary submit-btn">Save</button>
            </tr>
        </tbody>

ajax code

 function save_medical_records()
           {
               
               var doctorname           =   $("input[name='doctorname']").val();
               var doctorid             =   $("input[name='doctorid']").val();  
               var appid                =   $("input[name='appid']").val();
               var uid                  =   $("input[name='uid']").val();
               var name                 =   $("input[name='name']").val();             
               var quantity             =   $("input[name='quantity']").val();
               var days                 =   $("input[name='days']").val();
               
                
                const take_meds = $("[name='take_medicine[]']:checked").map(function() { return this.value}).get()
                 console.log(take_meds);
                
               
                   $.ajax({
                       url:"<?php echo base_url() ?>add-prescription",
                       data:"doctorname="+doctorname+"&doctorid="+doctorid+"&appid="+appid+"&uid="+uid+"&name="+name+"&quantity="+quantity+"&days="+days+"&take_meds="+take_meds,
                       //data: $("[name=doctorname]").serialize(),$("[name=doctorid]").serialize(),$("[name=appid]").serialize(),$("[name=uid]").serialize(),$("[name=name]").serialize(),$("[name=quantity]").serialize(),$("[name=days]").serialize(),$("[name=take_meds]").serialize(),
                       
                       
                       
                       type:"post",
                       success:function(response){ 
                           if(response==1)
                              
                              $("#msg").css("display","block"); 
                           
                       }
                       });
               }

            
    

controllers

public function add_prescription()
    {
        $result = $this->doctor_health_model->add_prescription();
        echo $result;

    }

models

public function add_prescription()
    {
        $db2 = $this->load->database('dpr',TRUE);
        $medicine       = $this->input->post('name');
        $uid            = $this->input->post('uid');
        $appid          = $this->input->post('appid');
        $doctor_id      = $this->input->post('doctorid');
        $doctor_name    = $this->input->post('doctorname');
        $quantity       = $this->input->post('quantity');
        $days           = $this->input->post('days');
        $take_medicine  = $this->input->post('take_medicine');  
        $today_date     = date("Y-m-d");
        
     $insert =$db2->query('INSERT INTO dpr_save_farmacytest (medicine,user_id,appointment_id,doctor_id,doctor_name,quantity,days,take_medicine_time,created_date) 
            VALUES ("'.$medicine.'","'.$uid.'","'.$appid.'","'.$doctor_id.'","'.$doctor_name.'","'.$quantity.'","'.$days.'","'.$take_medicine.'","'.$today_date.'")');
            //echo $db2->last_query();
            return $insert;

        }
    }
13
  • That is how jQuery works - this will return ONE value, from the FIRST of the elements with the same name var take_medicine = $("input[name='take_medicine[]']").val(); Commented Aug 24, 2020 at 9:51
  • As per the jQuery documentation for that method, .val() only takes the value from the first matched element in any set. So if $("input[name='take_medicine[]']") matches many checkboxes, .val() will only get the value from the first one. To be honest, instead of trying to extract all the data one-by-one from your form, why not just use jQuery's serialize() method to handle it automatically? api.jquery.com/serialize Commented Aug 24, 2020 at 9:52
  • P.S. Warning: Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. Commented Aug 24, 2020 at 9:52
  • 1
    P.P.S. Your database is also denormalised - you shouldn't really be storing multiple values (e.g. morning, night) in a single field like that. Please read up on relational database design before continuing. Commented Aug 24, 2020 at 9:53
  • share edit code please sir Commented Aug 24, 2020 at 9:56

1 Answer 1

1

Apart from the SQL Injection issues, the problem storing multiple values in one table field etc, your immediate question is answered by:

That is how jQuery works - this will return ONE value, from the FIRST of the elements with the same name

var take_medicine =   $("input[name='take_medicine[]']").val();

You need to get each checked checkbox - for example

const take_meds = $("[name='take_medicine[]']:checked")
       .map(function() { return this.value}).get();
console.log(take_meds);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-check form-check-inline">
  <label class="form-check-label"><input class="form-check-input checkbox_value" checked type="checkbox" name="take_medicine[]" id="morning" value="Morning"> Morning</label>
</div>
<div class="form-check form-check-inline">
  <label class="form-check-label"><input class="form-check-input checkbox_value" type="checkbox" name="take_medicine[]" id="afternoon" value="Afternoon"> Afternoon</label>
</div>
<div class="form-check form-check-inline">
  <label class="form-check-label"><input class="form-check-input checkbox_value" checked type="checkbox" name="take_medicine[]" id="evening" value="Evening"> Evening</label>
</div>

You could possibly have a simpler life if you use serialize

IF You have <form id="myForm" - you change the WHOLE AJAX code to

$("#myForm").on("submit", function(e) {
  e.preventDefault();
  $.ajax({
    url: "<?php echo base_url() ?>add-prescription",
    data: $(this).serialize(),
    type: "post",
    success: function(response) {
      if (response == 1) $("#msg").css("display", "block");
    },
    error: function(jxhr) {
      console.log("Error", jxhr)
    }
  })
});
Sign up to request clarification or add additional context in comments.

1 Comment

Comments are not for extended discussion; this conversation has been moved to chat.

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.