Receiving JSON output twice

I am currently working with CodeIgniter and facing an issue with my form fields, which are Employee_name, fromDate, and endDate. I am using AJAX to send this data without sharing the actual code. The problem arises when retrieving and displaying records from the database using JSON through AJAX calls. Although the output from the database is correct, I encounter some issues related to JSON parsing.

In the image below, the total number of records fetched from the database is shown as 9, which is accurate. However, while attempting to display these records using JSON, a total of 18 records appear. The first set of 9 records show up as undefined, followed by another set of 9 records that contain the actual desired output.

Can someone help me troubleshoot this issue?

https://i.stack.imgur.com/45yAR.png View

<!--form code here-->
<form name="employee_attendance"></form>
<!--end form code here-->

$("form[name='employee_attendance']").validate({
  rules: {
    employee_Name: {
      required: true
    },
    fromDate: {
      required: true
    },
    toDate: {
      required: true
    }
  },
  submitHandler: function(form) {
    var employee_Name = $('#employee_Name').val();
    var fromDate = $('#fromDate').val();
    var toDate = $('#toDate').val();                           
    $.ajax({
      url: baseUrl + "/Reports_control/report_attendance",
      method: "POST",
      //dataType: "json", 
      data: {
        employee_Name: employee_Name,
        fromDate: fromDate,
        toDate: toDate
      },
      success: function(response) {
        $('.search_record tbody tr').hide();
        var data = JSON.parse(response);
        if (data.status === 'error') {
          alert(data.msg);
        }
        if (data.status === 'success') {
          $('.addendence_report_list').show();
          var trHTML = '';
          $.each(data.records, function(i, o) {
            trHTML += '<tr><td>' + o.Sr_no +
              '</td><td>' + o.name +
              '</td><td>' + o.employee_id +
              '</td><td>' + o.last_activity +
              '</td><td>' + o.total_days +
              '</td></tr>';
          });
          $('.search_record tbody').append(trHTML);
        }
      }
    });
  }
});

Controller

public function report_attendance()
{
   $employee_id=trim($this->input->post('employee_Name'));
   $fromDate=trim(date('Y-m-d', strtotime($this->input->post('fromDate'))));
   $toDate=trim(date('Y-m-d', strtotime($this->input->post('toDate'))));
   if((!empty($employee_id)) && (!empty($fromDate)) && (!empty($toDate))){
     $result=$this->Reports_model->get_employee_attendance($employee_id,$fromDate,$toDate); 
    }
    if (empty($result) || $result == 0){
    $arr_result['status'] = "error";
    $arr_result['msg'] = "No record found";
    }
 else 
    {
        $n=1;
      foreach ($result as $row)
        {
        $result[] = array(
              "Sr_no" => $n,
              "name" => $row->firstname.' '.$row->lastname,
              "employee_id" => $row->employee_id,
              "last_activity"=>$row->login_time,
              "total_days"=>$row->total_days
            );
        $n++;
          }
    $arr_result['status'] = 'success';
    $arr_result['records'] = $result;
        }
      echo json_encode($arr_result);
       exit;
}

view

<div class="search_record">
  <table cellspacing="0" id="attendence_report_list">
    <thead>
      <tr>
        <th class="" width="5%">Sr. No.</th>
        <th class="" width="11%">Name</th>
        <th class="" width="11%">Emp Id</th>
        <th class="" width="9%">Date </th>
        <th class="" width="9%">Working hours</th>
        <th class="" width="9%">Leave Days</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <tr>
        </tr>
    </tbody>
  </table>
</div>

Answer №1

Update the array name used in the foreach loop from $result[] to results[] and test it out.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting an array to an object using underscore: a beginner's guide

My array consists of different subjects: var subject = ["Tamil", "English", "Math"]; Now, I want to transform this array into an object, structured like this: [{ "name": "Tamil" }, { "name": "English" }, { "name": "Math" }] ...

Troubleshooting problem with input and textarea losing focus in Ajax requests

Experiencing an issue with submitting information using ajax. For instance, there are 20 rows. When a row is clicked, it displays all details about services. $('tr').click(function() { var servicesUpdateId = $(this).attr('data&a ...

What is the purpose of implementing asynchronous loading for JavaScript in my webpack setup?

I am facing difficulties with handling unusual codes. I am trying to add some query parameters using $.ajaxPrefilter in all jQuery ajax requests. I came across the following code snippet which seems to ensure synchronous loading order, but in my entry.js ...

Laravel's hasManyThrough relationship allows for linking to another model

I am currently facing a situation where the Parent and Student models are in a many-to-many relationship, each of them belonging to the User model. The Branch is connected to many Students through the User via hasManyThrough(Student::class, User::class);. ...

Enhance your photos with dynamic resizing within the original boundaries

Is there a jQuery plugin or function that allows for photo enlargement and movement within its original limits while hovering over the main product image like it is done here? ...

Unravel various models in PHP Symfony by decoding JSON data into objects

Is there a way to effectively convert a multidimensional JSON into an object or model? When attempting to convert a JSON with nested structures, only the outer layer is successfully converted while inner layers remain as arrays. How can this issue be reso ...

Introducing an exception to every jQuery post() method

Our app utilizes AJAX with jQuery to manage user information. We determine the success or failure of an API call by checking data.success or data.error respectively. Additionally, we implement the jQuery error() function in each post() method to handle any ...

My goal is to eliminate unnecessary code and transfer it into its own jQuery function

Currently, I am working on optimizing my code by removing redundancies and moving sections to separate functions. //Consolidating Infotypes for filtering and checking if any option is selected if(this.$infoOptions.val() != null){ ...

Sending Python Object from Django View to Javascript Script in Template

Here is a basic code snippet created solely to illustrate a problem. While the task at hand can be achieved without JavaScript, I am exploring how to accomplish it using JavaScript for my actual code where it is necessary. In view.py Inside the play_game ...

Using cURL for PHP JSON parsing

I am trying to develop a basic webpage that displays the current region based on the user's IP address. To achieve this, I am utilizing an API provided by freegeoip.net. Even though I have successfully configured the code to send the user's IP to ...

Using SQL aliases in PHP

Could someone please assist me in locating the error in my SQL statement? I am encountering an issue with my query and believe it may be related to the use of aliases while trying to display the names of two football teams in a fixture list. This is how my ...

Ensuring successful PHP mail delivery simulation on development server

Currently working on a Lumen API within a VirtualBox environment that will send emails intermittently. However, during development, I prefer to have the server simulate sending the mail rather than actually doing so. In the past, I've used conditional ...

I am wondering why my JSON appears in Kendo UI as Datasource.options.data but not Datasource.data

I'm new to Kendo and struggling to display my JSON data in the Kendo Grid. When I try to access my $scope.actionData using a regular HTML table, it displays on the page. My ultimate goal is to achieve something similar to this. The column headers ar ...

The current JSON object cannot be deserialized into the specified type because the type is expecting a JSON array

I'm currently learning how to handle JSON strings in C# and encountered an issue while trying to deserialize a JSON string: Unable to deserialize the current JSON object (e.g. {'name':'value'}) into type 'System.Collections.Ge ...

Include category to the smallest element

I am attempting to use JQuery to find the height of the tallest element and then add that height to other elements that are shorter. My goal is to assign the class, main-nav-special-padding, to these shorter elements using my current JQuery code. I tried t ...

Is there a way to choose an entire directory containing images using codeigniter?

For my current project, I am looking to choose an entire folder that contains pictures and apply a transformation to each picture within the folder. This process is akin to using scripts in Photoshop for making bulk adjustments to images. ...

Looking for subsequence in dropdown choices with no assigned values

I need assistance with searching for a specific substring within text that is fetched from options generated by MySQL. How can I retrieve the selected option's text value in order to search for my desired substring? $(document).ready(function() { ...

Querying for MySQL data within specific time intervals of 5 to 10 minutes and 1 to 2 hours

I need help creating a MySQL query to display the number of users who have spent time in the showroom within the last 5 minutes, 30 minutes, and 1 hour. The timestamps are recorded as entry_user and exit_user. Can someone suggest how I can achieve this to ...

Retrieve information using AJAX via POST method

I find myself in a bit of a pickle at the moment. I've been researching for hours, and I still can't seem to figure out this seemingly basic issue. It would be greatly appreciated if someone could offer me some quick advice. So here's my dil ...

Converting a PHP array into a jQuery array using <<<EOT syntax

I am facing an issue with my PHP code that outputs jQuery using the <<