Beginner
Beginner

Reputation: 191

AJAX not working as expected

I've spent a day checking this code, but still can't find where the error is.

<div class="col-md-6">
  <br/>
  <label for="name">Class ID</label>
  <select class="form-control" id="csid" name="csid">
    <option>----------Please select a Class Code---------</option>
    <?php
      $query = $con->query("SELECT * FROM class WHERE class_status='Active' ");
      $rowCount = $query->num_rows;
      if($rowCount > 0) {
        while($row = $query->fetch_assoc()) { 
          echo '<option value="'.$row['class_id'].'">'.$row['class_code'].'</option>';
        }
      }
      else {
        echo '<option value="">Class ID not available</option>';
      }
    ?>
  </select>
</div>
<div class="col-md-6">
  <br/>
  <label for="name">Subject Name</label>
  <input type="text" class="form-control" name="subid" id="subid" disabled/>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
     $(document).ready(function(){
       $('#csid').change(function(){
         var classid = $(this).val();
         $.ajax({
           type:'POST',
           url:'ajax.php',
           data:{classid:classid},
           success:function(data){
             $('#subid').val(data);
           }
         });
       });
    });
</script>

And here is my ajax.php file:

<?php

include('dataconnect.php');

if (isset($_POST['classid'])) 
{
    $qry = "select * from class where class_id=". $_POST['classid'];
    $rec = mysql_query($qry);
    if (mysql_num_rows($rec) > 0) {
        while ($res = mysql_fetch_array($rec)) {
            echo $res['class_status'];
        }
    }
}

?>

Can anyone let me know where the error is, as I really can't find it. Thank you.

Upvotes: 0

Views: 58

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42304

If you are using PHP 7, your code won't have any output due to the fact that the mysql_ constructor is removed in PHP 7 (and deprecated as of PHP 5.5).

Switching to either MySQLi or PDO will fix this problem.

In addition to this, please ensure that you also use prepared statements to prevent SQL injection. :)

Upvotes: 1

Related Questions