0

I have a dropdown selection where the user can select a name and related data will be loaded with the selection. Everything works fine except it always keeps the first data after the second or third selection. How do I remove the first selected data's when I am selecting a value the second time?

<table  class="table table-striped table-bordered"  id="example">
    <thead>
        <tr>            
            <td>Course Code</td>
            <td>Name</td>
            <td>Grade</td>                      
        </tr>
    </thead>
</table>  

<script type="text/javascript">
    $('#student').on('change', function(e) {               
        $('#example tr:last').remove().end();
        var std_id = $('#student option:selected').attr('value');

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({ 
            type: "POST", 
            url: "{{url('ajax-student-result')}}",
            data: {
                std_id: std_id
            },
            success: function(data) {                  
                $.each(data, function(index, subcatObj) {
                    $('#example tr:last').after('<tr><td id="code">' + subcatObj.c_code + '</td><td id="course_name">' + subcatObj.c_name + '</td><td id="grade">' + subcatObj.grade + '</td></tr>');
                });
            } 
        });
    });
</script>  
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
User57
  • 2,453
  • 14
  • 36
  • 72

2 Answers2

1

I guess you are using Symfony and Twig.

I think a CSRF token is to be used only once so if you don't renew your csrf token for each ajax post request it may be the reason why it works only once.

Edit : Found this question which might help you : Generate new CSRF token without reloading the entire form

Community
  • 1
  • 1
Mantisse
  • 309
  • 4
  • 15
0

Change the code to include removal:

success: function(data) {
            $('#example tr:last')remove(); 
            $.each(data, function(index, subcatObj) {
                $('#example tr:last').after('<tr><td id="code">' + subcatObj.c_code + '</td><td id="course_name">' + subcatObj.c_name + '</td><td id="grade">' + subcatObj.grade + '</td></tr>');
            });
        }
Gerard
  • 15,418
  • 5
  • 30
  • 52