AJAX - Agregar dinamicamente calendario datepicker con ajax y php

 
Vista:
sin imagen de perfil
Val: 2
Ha aumentado su posición en 2 puestos en AJAX (en relación al último mes)
Gráfica de AJAX

Agregar dinamicamente calendario datepicker con ajax y php

Publicado por Levis (1 intervención) el 26/01/2021 21:59:30
Hola, Estoy tratando de modificar un codigo que descargué, El código permite agregar/remover dinamicamente un inputs y una lista desplegable, esto se hace en archivo index.php donde se selecciona un nombre de una cuenta ($row["name"]) desde un option select (lista despleglable) tomado de Mysql y de alli tomo el Id de la cuenta ($row["account_id"]), tengo tambien un Input donde puedo introducir un monto(name="amount[]"), luego estos datos $row["account_id" y el input (name="amount[]) son enviados mediante jquery a archivo insert.php para guardarlos en tabla Mysql. Quisiera agregar un Input con un calendario (Usando datepicker) para aparte de seleccionar el nombre de la cuenta, el monto , poder seleccionar la fecha de cuando se introdujo el nombre y el monto, quisiera que cada datapicker fuera independiente para cada nombre de cuenta, por ejemplo: si en Agua se gastaron 20 el dia 25 de enero, en eletricidad monto 30 el dia 26 de enero. Este es el codigo de index.php:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<?php
    //index.php
 
    //Tomar  account_id from de nombre de cuanta seleccionado en lista despleglable
    $connect = new PDO("mysql:host=localhost;dbname=condominium", "root", "password");
    function fill_unit_select_box($connect)
    {
     $output = '';
     $query = "SELECT * FROM accounts ORDER BY name ASC";
     $statement = $connect->prepare($query);
     $statement->execute();
     $result = $statement->fetchAll();
     foreach($result as $row)
     {
      $output .= '<option value="'.$row["account_id"].'">'.$row["name"].'</option>';
     }
     return $output;
    }
    ?>
    <!DOCTYPE html>
    <html>
     <head>
      <title>Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
     </head>
     <body>
 
 
      <br />
      <div class="container">
       <h3 align="center">Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</h3>
       <form method="post" id="insert_form">
        <div align="left">
           <h4 align="center">Enter Expense Details</h4>
                    <!-- Asi abre directamentete Modal usando  data-target="#userModal -->
                    <!-- <button type="button" class="btn btn-success" data-toggle="modal" data-target="#AddModal">Agregar Emp.</button>-->
                    <!-- Con Input hay que enviarlo primero a ajax y ajax abre modal -->
                    <label style="color: blue" >Select Date</label>
                    <div><input type="text" name="selDate" id="datepicker"class="tcalx" value="" /></div>
                    <!-- <input type="text" class="form-control" placeholder="1000" name="preciobsmayor" id="preciobsmayor" readonly="readonly"><br>-->
                    <br />
                    <br />
        </div>
        <div class="table-repsonsive">
         <span id="error"></span>
         <table class="table table-bordered" id="item_table">
          <tr>
           <th>Account </th>
           <th>Amount</th>
           <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
          </tr>
         </table>
         <div align="center">
          <input type="submit" name="submit" class="btn btn-info" value="Insert" />
         </div>
        </div>
       </form>
      </div>
     </body>
    </html>
 
    <script>
    $(document).ready(function(){
 
     $(document).on('click', '.add', function(){
      var html = '';
    //Add Dropdownlist and Input
     html += '<tr>';
      html += '<td><select   name="account_id[]" class="form-control account_id"><option value="">Select Product</option><?php echo fill_unit_select_box($connect); ?></select></td>';
      html += '<td><input type="text" name="amount[]" class="form-control amount" /></td>';
      html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
      $('#item_table').append(html);
     });
 
     $(document).on('click', '.remove', function(){
      $(this).closest('tr').remove();
     });
 
     //Dar mensaje d entrar datos
     $('#insert_form').on('submit', function(event){
      event.preventDefault();
      var error = '';
      $('.account_id').each(function(){
       var count = 1;
       if($(this).val() == '')
       {
        error += "<p>Select Account Name at "+count+" Row</p>";
        return false;
       }
       count = count + 1;
      });
 
      $('.amount').each(function(){
       var count = 1;
       if($(this).val() == '')
       {
        error += "<p>Enter Amount "+count+" Row</p>";
        return false;
       }
       count = count + 1;
      });
 
     //Enviar data para insertar en Mysqk
      var form_data = $(this).serialize();
      if(error == '')
      {
       *$.ajax({
        url:"insert.php",
        method:"POST",
        data:form_data,
        success:function(data)
        {
         if(data == 'ok')
         {
          $('#item_table').find("tr:gt(0)").remove();
          $('#error').html('<div class="alert alert-success">Expense Saved</div>');
         }
        }
       });
      }
      else
      {
       $('#error').html('<div class="alert alert-danger">'+error+'</div>');
      }
     });
 
    });
 
 
    //Tengo este datepicker pero no esta en agregar dinamicamente
    $(function() {
        $("#datepicker").datepicker({
           //showOn: both - datepicker will appear clicking the input box as well as the calendar icon
           //showOn: button - datepicker will appear only on clicking the calendar icon
           showOn: 'button',
           //you can use your local path also eg. buttonImage: 'images/x_office_calendar.png'
           buttonImage: 'https://theonlytutorials.com/demo/x_office_calendar.png',
           buttonImageOnly: true,
           changeMonth: true,
           changeYear: true,
           showAnim: 'slideDown',
           duration: 'fast',
           dateFormat: 'dd-mm-yy'
        });
    });
 
    </script*
 
>

Este es archivo insert.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
//Insert Data
 
if(isset($_POST["account_id"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=condominium", "root", "mysq1passw0rd");
 $order_id = uniqid();
 for($count = 0; $count < count($_POST["account_id"]); $count++)
 {
  $query = "INSERT INTO expense
  (account_id, amount)
  VALUES (:account_id, :amount)
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':account_id'  => $_POST["account_id"][$count],
    ':amount' => $_POST["amount"][$count],
   )
  );
 }
 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'ok';
 }
}
?>
En archivo index.php tengo un input con datepicker pero no forma parte del codigo donde agrego/remuevo dinamicamente, parte del codigo de index.php donde esta el input para el datepicker:

1
2
<label style="color: blue" >Select Date</label>
                <div><input type="text" name="selDate" id="datepicker"class="tcalx" value="" /></div>

Otra pregunta, Si dejo el Input del datepicker que muestro arriba fuera del agregar/remover dinamicamente, , Pero selecciono una fecha, como hago para pasar la variable de fecha seleccionada al archivo insert.php?

De antemano gracias.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder