简体   繁体   中英

How to get text from html input field

I'm trying to create a pdf report using php. First, user will need to key in the name in the input box, and the name will be passed to the 2nd php page which will search mysql database.

problem : after user key in the name, i try to call the data (var student_id = $('#nama_student').val()), but the script states it is undefined.

p/s : sorry if code not sanitized, I'm still learning, by myself..

codes:

php

//attendance.php

include('header.php');

$student_list_id = '';
$error_student_list_id = '';
$error = 0;
$success = '';

?>

<div class="container" style="margin-top:30px">
  <div class="card">
    <div class="card-header">
      <div class="row">
        <div class="col-md-9"><b>Attendance List</b></div>
        <div class="col-md-3" align="right">
          <button type="button" id="report_button" class="btn btn-danger btn-sm">Report</button>
        </div>
      </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
        <span id="message_operation"></span>
        <table class="table table-striped table-bordered" id="attendance_table">
          <thead>
            <tr>
              <th>Student Name</th>
              <th>Card No</th>
              <th>Date</th>
              <th>Time In</th>
              <th>Time Out</th>
            </tr>
          </thead>
          <tbody>

          </tbody>
        </table>
        </div>
    </div>
  </div>
</div>

</body>
</html>

<script type="text/javascript" src="js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="css/datepicker.css" />

<style>
    .datepicker
    {
      z-index: 1600 !important; /* has to be larger than 1050 */
    }
</style>



<div class="modal" id="reportModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Make Report</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        <div class="form-group">
        <form method="post">
            Name: <input type="text" name="name1"><br>
            <?php $nama_student = $_POST["name1"]; 
            ?>
            </form>
        </div>
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" name="create_report" id="create_report" class="btn btn-success btn-sm">Create Report</button>
        <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>

<script>
$(document).ready(function(){

  var dataTable = $('#attendance_table').DataTable({
    "processing":true,
    "serverSide":true,
    "order":[],
    "ajax":{
      url:"attendance_action.php",
      method:"POST",
      data:{action:"fetch"}
    }
  });

  $('#attendance_date').datepicker({
    format:'yyyy-mm-dd',
    autoclose:true,
    container: '#formModal modal-body'
  });

  function clear_field()
  {
    $('#attendance_form')[0].reset();
    $('#error_attendance_date').text('');
  }

  $('#add_button').click(function(){
    $('#modal_title').text("Add Attendance");
    $('#formModal').modal('show');
    clear_field();
  });

  $('#attendance_form').on('submit', function(event){
    event.preventDefault();
    $.ajax({
      url:"attendance_action.php",
      method:"POST",
      data:$(this).serialize(),
      dataType:"json",
      beforeSend:function(){
        $('#button_action').val('Validate...');
        $('#button_action').attr('disabled', 'disabled');
      },
      success:function(data)
      {
        $('#button_action').attr('disabled', false);
        $('#button_action').val($('#action').val());
        if(data.success)
        {
          $('#message_operation').html('<div class="alert alert-success">'+data.success+'</div>');
          clear_field();
          $('#formModal').modal('hide');
          dataTable.ajax.reload();
        }
        if(data.error)
        {
          if(data.error_attendance_date != '')
          {
            $('#error_attendance_date').text(data.error_attendance_date);
          }
          else
          {
            $('#error_attendance_date').text('');
          }
        }
      }
    })
  });

  $('.input-daterange').datepicker({
    todayBtn:"linked",
    format:"yyyy-mm-dd",
    autoclose:true,
    container: '#formModal modal-body'
  });

  $(document).on('click', '#report_button', function(){
    $('#reportModal').modal('show');
  });

  $('#create_report').click(function(){

    var student_id = $('#nama_student').val();

    $('#formModal').modal('hide');
    window.open("report.php?action=attendance_report&student_id="+student_id);



  });

});
</script>

You have an issue in your code here:

...
<form method="post">
  Name: <input type="text" name="name1"><br>
  <?php $nama_student = $_POST["name1"]; ?>
</form>
...

jQuery selector will not work like this, jQuery selector should be used the same way you are using them in CSS, so when you select input by a dynamic id from PHP you should print that name in the id attribute like the following:

<form method="post">
  Name: <input type="text" name="name1" id="student_name"><br>
  <?php $nama_student = $_POST["name1"];  ?></br>
</form>

then in javascript:

...
$('#create_report').click(function(){
  var student_id = $('#nama_student').val();
...

Update : based on @ecarrizo: you can just do PHP echo for the variable value inside your javascript like this:

...
$('#create_report').click(function(){
    var student_id = <?php echo $_POST["name1"]; ?>
    $('#formModal').modal('hide');
    window.open("report.php?action=attendance_report&student_id="+student_id);
});
...

You have several issues on your script so let start from scratch:

Issue #1 - You are declaring a PHP Variable but doing nothing with it.

You are retrieving name1 POST value in your php script and storing it on the variable $nama_student but this variable is not used later in your code.

You might want to print it using the echo PHP instruction.

// Example 
<?php echo $_POST["name1"]; ?>


Issue #2 - There is not an element with id #nama_student in your HTML this element do not exists so the element is undefined and you cannot access its value using the jquery instuction $('#nama_student') .

Since your intention here is to retrieve the value of the form element name1 You should assign the identifier that you are proposing to that element, so it is no longer undefined!

// Example
<input type="text" name="name1" id="nama_student">


Issue #3 - You are not assigning back the value to the element that you are trying to retrieve the value from

Even if your intention was to 'echo' the value after the input, that will not assign the value to the input element, then, even if you can access your form element, you are not going to get any value from val() . To solve this you need to assign the value to the input.

<input type="text" name="name1" value="you print the php variable here">


Now that you understand the problem you are having, try to put it all together:

<input type="text" name="name1" id="nama_student" value="<?php echo $_POST["name1"]; ?>">

Then your $('#nama_student').val() , should have a value

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