Skip to content

How to reset the counter to 0 after Ajax Refresh or Submistion to database,

I have this code that sends multiple data in MySQL Database using JQuery Ajax, all works fine but when i try to refresh the page using ajax and add new record, Its populated the number of times equivalent to the last counter.

Below is my index.php page;

<div id="sample_table_data">
    <div class="row">
        <div class="panel border-cyan-dark">
            <div class="panel-heading bg-cyan text-white border-cyan-dark">
                    <div class="panel-title">
                        <h4>PHP - Sending multiple forms data through jQuery Ajax</h4>
                  </div>
            </div>
            <div class="panel-body">
                <div style="padding-bottom: 10px;" align="right">
                        <button name="add" id="add" class="btn btn-success btn-sm">
                            <i class="fa fa-plus-square"></i>Add Measures
                        </button>
                </div>
                <form method="POST" id="user_form">
                    <div class="row">
                        <div class="table-responsive margin-bottom-20" >
                            <table class="table table-striped table-bordered table-condensed table-hover" id="user_data">
                                <thead>
                                    <tr>
                                        <th>First Name</th>
                                        <th>Last Name</th>
                                        <th>Details</th>
                                        <th>Remove</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                    <div class="row">
                        <input type="submit" name="insert" id="insert" class="btn btn-primary btn-sm" value="Insert">
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Form Dialogue Box -->
<div id="user_dialog">
    <div class="row">
        <div class="col-sm-12">
            <div class="form-group">
                <label>Enter First Name</label>
                <input type="text" name="first_name" id="first_name" class="form-control input-sm">
                <span id="error_first_name" class="text-danger"></span>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12">
            <div class="form-group">
                <label>Enter Last Name</label>
                <input type="text" name="last_name" id="last_name" class="form-control input-sm">
                <span id="error_last_name" class="text-danger"></span>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12">
            <div class="form-group">
                <input type="hidden" name="row_id" id="hidden_row_id">
                <button type="button" name="save" id="save" class="btn btn-info btn-sm">Save</button>
            </div>
        </div>
    </div>
</div>

<!-- Alert Box -->
<div id="action_alert" title="Action"></div>

<script>  
    $(document).ready(function(){ 
     
        var count = 0;

     $('#user_dialog').dialog({
        autoOpen:false,
        width:800
    });


     $('#add').click(function(){
        $('#user_dialog').dialog('option', 'title', 'Add Data');
        $('#first_name').val('');
        $('#last_name').val('');
        $('#error_first_name').text('');
        $('#error_last_name').text('');
        $('#first_name').css('border-color', '');
        $('#last_name').css('border-color', '');
        $('#save').text('Save');
        $('#user_dialog').dialog('open');
    });

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

        var error_first_name = '';
        var error_last_name = '';
        var first_name = '';
        var last_name = '';
        if($('#first_name').val() == '') {
             error_first_name = 'First Name is required';
             $('#error_first_name').text(error_first_name);
             $('#first_name').css('border-color', '#cc0000');
             first_name = '';
        } else {
             error_first_name = '';
             $('#error_first_name').text(error_first_name);
             $('#first_name').css('border-color', '');
             first_name = $('#first_name').val();
        } 
        if($('#last_name').val() == '') {
             error_last_name = 'Last Name is required';
             $('#error_last_name').text(error_last_name);
             $('#last_name').css('border-color', '#cc0000');
             last_name = '';
        } else  {
             error_last_name = '';
             $('#error_last_name').text(error_last_name);
             $('#last_name').css('border-color', '');
             last_name = $('#last_name').val();
        }


        if(error_first_name != '' || error_last_name != '') {
             return false;
        
        } else {
             if($('#save').text() == 'Save')
             {
                count++;
                output = '<tr id="row_'+count+'">';
                output += '<td>'+first_name+' <input type="hidden" name="hidden_first_name[]" id="first_name'+count+'" class="first_name" value="'+first_name+'" /></td>';
                output += '<td>'+last_name+' <input type="hidden" name="hidden_last_name[]" id="last_name'+count+'" value="'+last_name+'" /></td>';
                output += '<td><button type="button" name="view_details" class="btn btn-warning btn-xs view_details" id="'+count+'">View</button></td>';
                output += '<td><button type="button" name="remove_details" class="btn btn-danger btn-xs remove_details" id="'+count+'">Remove</button></td>';
                output += '</tr>';
                $('#user_data').append(output);
            }
            else
            {
                var row_id = $('#hidden_row_id').val();
                output = '<td>'+first_name+' <input type="hidden" name="hidden_first_name[]" id="first_name'+row_id+'" class="first_name" value="'+first_name+'" /></td>';
                output += '<td>'+last_name+' <input type="hidden" name="hidden_last_name[]" id="last_name'+row_id+'" value="'+last_name+'" /></td>';
                output += '<td><button type="button" name="view_details" class="btn btn-warning btn-xs view_details" id="'+row_id+'">View</button></td>';
                output += '<td><button type="button" name="remove_details" class="btn btn-danger btn-xs remove_details" id="'+row_id+'">Remove</button></td>';
                $('#row_'+row_id+'').html(output);
            }
     
          $('#user_dialog').dialog('close');   
       }
});

    
    $(document).on('click', '.view_details', function(){
        var row_id = $(this).attr("id");
        var first_name = $('#first_name'+row_id+'').val();
        var last_name = $('#last_name'+row_id+'').val();
        $('#first_name').val(first_name);
        $('#last_name').val(last_name);
        $('#save').text('Edit');
        $('#hidden_row_id').val(row_id);
        $('#user_dialog').dialog('option', 'title', 'Edit Data');
        $('#user_dialog').dialog('open');
    });


    $(document).on('click', '.remove_details', function(){
        var row_id = $(this).attr("id");
        if(confirm("Are you sure you want to remove this row data?")) {
         $('#row_'+row_id+'').remove();
         }  else  {
             return false;
         }
    });
    
    $('#action_alert').dialog({
        autoOpen:false
    });

    
    $('#user_form').on('submit', function(event){
        event.preventDefault();
        var count_data = 0;
        $('.first_name').each(function(){
         count_data = count_data + 1;
     });
        if(count_data > 0)
        {
         var form_data = $(this).serialize();
         $.ajax({
            url:"pages/insert.php",
            method:"POST",
            data:form_data,
            success:function(data)
            {
             $('#user_data').find("tr:gt(0)").remove();
            count =0;
             $('#action_alert').html('<p>Data Inserted Successfully</p>');
             $('#action_alert').dialog('open');
            }
        })
     }
     else
     {
         $('#action_alert').html('<p>Please Add atleast one data</p>');
         $('#action_alert').dialog('open');
     }
    });
    


 });
</script>

and this is my insert.php code

<?php

//insert.php

$connect = new PDO("mysql:host=localhost;dbname=test", "root", "****");

$query = "
INSERT INTO tbl_sample 
(first_name, last_name) 
VALUES (:first_name, :last_name)
";

for($count = 0; $count<count($_POST['hidden_first_name']); $count++)
{
 $data = array(
  ':first_name' => $_POST['hidden_first_name'][$count],
  ':last_name' => $_POST['hidden_last_name'][$count]
 );
 $statement = $connect->prepare($query);
 $statement->execute($data);
}

?>

Kindly help me how I can reset the counter to 0 after Ajax refresh. Thanks.

Answer

put the var count ouside the $(document)

 var count = 0;
 $(document).ready(function(){ 
 

and in your submit function

$('#user_form').on('submit', function(event){
    event.preventDefault();
    var count_data = 0;
    $('.first_name').each(function(){
     count_data = count_data + 1;
 });
    if(count_data > 0)
    {
     var form_data = $(this).serialize();
     $.ajax({
        url:"pages/insert.php",
        method:"POST",
        data:form_data,
        success:function(data)
        {
         $('#user_data').find("tr:gt(0)").remove();
         $('#action_alert').html('<p>Data Inserted Successfully</p>');
         $('#action_alert').dialog('open');
        }
        count =0;
    })
 }
 else
 {
     $('#action_alert').html('<p>Please Add atleast one data</p>');
     $('#action_alert').dialog('open');
 }
});

and in additional, you should be using .prop instead of .attr