Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appreciate any assistance. Thank you in advance.

View - controller (Admin/gstInvoice)

<div class="row">
                <form id="myform" method="POST" action="">
                    <div class="col-lg-6">
                        <select id="select" class="form-control">
                            <option value="No Data">-- Select Client --</option>
                            <?php foreach ($client as $clientx): ?>
                                <option id="<?= $clientx->cid; ?>" name="<?= $clientx->client_name; ?>"><?= $clientx->client_name; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-lg-6">
                        <input type="button" class="submit btn btn-success" id="submit" name="Submit" Value="Submit"/>
                    </div>
                </form>
            </div>
            <div id="result"></div>
            <script>
                $(document).ready(function(){
                $('#submit').click(function(event){
                    event.preventDefault();
                    $.ajax({
                        url : "Invoice/invoiceData",
                        method : 'POST',
                        datatype:'html',
                        success:function(Result){
                            $('#result').html(Result)
                        }
                    })
                })
            })
            </script>

I am aiming to display all existing invoices of a selected client when the client is chosen and the submit button is clicked, along with a functionality to create a new invoice.

In addition to creating salary slips for employees using PHP code, I now want to retrieve data for each invoice table without the need to refresh the page.

You can get a clearer idea of what I am looking for through the images below.

I intend to implement an Ajax script that fetches data from the database and displays it on the same page without requiring a page reload.

Images showcasing my employee salary table:

https://i.stack.imgur.com/QIcuc.png

Upon clicking on any employee, all their salary slips should be displayed:

https://i.stack.imgur.com/D6UTq.png

Your help would be greatly appreciated.

Answer №1

Form data is not being sent with the ajax request. Make sure to utilize $('#myform').serialize() for sending the data.

Furthermore, ensure that the <select> tag has a name attribute included in it.

The correct format for the

<select id="select" class="form-control" name="client">
should be used.

Follow this example:

$(document).ready(function(){
   $('#submit').click(function(event){
       event.preventDefault();
       $.ajax({
          url : "<?= base_url('Invoice/invoiceData') ?>",
          method : 'POST',
          data: $('#myform').serialize(),
          dataType:'html',
          success:function(Result){
              $('#result').html(Result)
           }
       });
     });
   });

Controller Section

To retrieve form data within the controller function, use the following syntax:

$client = $this-input->post('client');

Answer №2

<div class="row">
    <form id="myForm" method="POST" action="">
        <div class="col-lg-6">
            <select id="clientSelect" name="customer" class="form-control">
                <option value="No Data">-- Select Customer --</option>
                <?php foreach ($customers as $customer): ?>
                    <option value="<?= $customer->id; ?>" id="<?= $customer->id; ?>" name="<?= $customer->name; ?>"><?= $customer->name; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-lg-6">
            <input type="button" class="submitBtn btn btn-success" id="submitButton" name="SubmitButton" Value="Submit"/>
        </div>
    </form>
</div>
<div id="resultSection"></div>
<script>
    $(document).ready(function(){
    $('#submitButton').click(function(event){
        event.preventDefault();
        $.ajax({
            url : "<?= base_url('Invoice/customerData') ?>",
            data: $('#myForm').serialize(),
            type : 'POST',
            dataType:'html',
            success:function(dataResult){
                $('#resultSection').html(dataResult)
            }
        })
    })
})
</script>

<!-- Controller -->
<?php
public function customerData() { 
    $customer = $this->input->post('customer'); 
    $this->view->load('Admin/customerView',$customer, TRUE); 
}

Modified form and controller to handle customer selection, please verify.

Answer №3

Data Retrieval Function

public function retrieveCities(){

  $this->db->order_by('city_id','desc');
  $this->db->limit('1000');
  $this->db->select('*,cities.name as city_name');
  $this->db->from('cities');
  $this->db->join('states','states.id=cities.state_id','left');
  $this->db->join('countries','countries.id=states.country_id','left');
  $data=$this->db->get();
  return $data->result_array();
}

private function getDatatablesQueryCity(){
    $column_search = array('cities.name','states.name','countries.country_name');
    $order = array('city_id' => 'desc');
    $column_order = array(null, 'city_name', 'sname', 'country_name', null);
    $this->db->select('cities.city_id,cities.name as city_name,states.name as sname,states.id as state_id,countries.id as country_id,countries.country_name');
     $this->db->from('cities');
     $this->db->join('states','states.id=cities.state_id','left');
     $this->db->join('countries','countries.id=states.country_id','left');
     $i = 0;
     foreach ($column_search as $item)
     {
        if($_POST['search']['value']) // if datatable send POST for search
            {
                if($i===0)
                {
                    $this->db->group_start();
                    $this->db->like($item, $_POST['search']['value']);
                }
                else
                {
                    $this->db->or_like($item, $_POST['search']['value']);
                }
                if(count($column_search) - 1 == $i)
                $this->db->group_end();
        }
        $i++;
    }
    if(isset($_POST['order']))
    {
        $this->db->order_by($column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
    }
    else if(isset($order))
    {
        $order = $order;
        $this->db->order_by(key($order), $order[key($order)]);
    }
}
function retrieveDatatablesCity()
{
    $this->getDatatablesQueryCity();
    if($_POST['length'] != -1)
        $this->db->limit($_POST['length'], $_POST['start']);
    $query = $this->db->get();
    return $query->result();
}
function countFilteredCity()
{
    $this->getDatatablesQueryCity();
    $query = $this->db->get();
    return $query->num_rows();
}
public function countAllCity()
{
    $this->db->from('cities');
    return $this->db->count_all_results();
} 

Control Function

 public function displayCityList(){
        $this->load->view('admin/header');
        $this->load->view('admin/city');
        $this->load->view('admin/footer');
    }
    
    public function getCityAjaxData(){
        $list = $this->Admin_model->retrieveDatatablesCity();
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $city){
            $no++;
            $row = array();
            $row[] = $no;
            $row[] = $city->city_name;
            $row[] = $city->sname;
            $row[] = $city->country_name;

            /* Additional HTML Markup */
            
            $data[] = $row;
        }
        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->Admin_model->countAllCity(),
            "recordsFiltered" => $this->Admin_model->countFilteredCity(),
            "data" => $data,
        );
        echo json_encode($output);
    }

View Section

<div class="section-body">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped" id="example">
                            <thead>
                                <tr>
                                    <th>Serial Number</th>
                                    <th>City Name</th>
                                    <th>State Name</th>
                                    <th>Country</th>
                                    <th>Management</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
        
<!-- Modal for deletion confirmation -->
        
<div class="modal fade" id="delete" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    ...
</div>

...

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

Enhancing webpage design by dynamically changing borders and headers using JavaScript

I have implemented a fixed positioning for the table headers using the following code: onScroll={() => { document.querySelector('thead').style.transform = `translate(0,${this.scrollRef.scrollTop}px)`; }} However, when I scroll the ta ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

What is the best way to load $cookies into an Angular service?

After defining an Angular service where I need to access a cookie, I noticed that the $cookieStore is deprecated and that it's recommended to use $cookies instead. This is how my service is set up: 'use strict'; var lunchrServices = angul ...

Incorporating a timer feature into the code for my memory game

Seeking the optimal method to incorporate a timer into my memory game. This game comprises numerous squares, and when the user successfully completes it, a modal appears congratulating them on their win and providing an option to restart the game. The obj ...

Is there a way to restrict my input to only 10 numbers without allowing any characters?

Is there a way to restrict the phone number input to only allow 10 numbers and exclude any other characters? Currently, setting the maxLength attribute limits the characters to 10 but allows additional characters as well. If I change the type attribute to ...

Tips for successfully importing .eot and .woff documents using Babel?

When attempting to start my project, I encountered the following error message (You may need an appropriate loader to handle this file type.) for .eot, .woff, .ttf, and .svg files: ERROR in ./src/styles/fonts/nm/icons/nm-icons.svg?aaf8685e87a6901c76c52d00 ...

Why is it not possible for me to choose an element after it has been placed within a grid component?

Struggling to eliminate the blur effect on an image inside a grid element? It seems modifying the properties of an element within a grid class is causing some issues. To simplify, I conducted a basic test: I managed to change the ppp2 class when hovering ...

Move information from one webpage to a different page

After developing a site using NextJs, I successfully integrated Discord login functionality and was able to retrieve the user's guilds in the oauth file. Now, I am looking to send this list of guilds (in JSON format) to my dashboard page. In the oau ...

Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database: $scope.submit = function(){ var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name; console.log(url); $ht ...

An old-school Ajax request abruptly interrupted halfway through

function submitLogin(){ var username = document.getElementById('username').value; var password = document.getElementById('password').value; var testlabel = document.getElementById('testlabel').value; ...

Edit the settings for the dual-axis line chart's parameters

After countless hours of scouring the Internet and numerous attempts, I have come to the decision to seek help by posting my issue on this forum. I must confess, I am not the best developer. My approach usually involves finding pre-existing code that I ca ...

I'm puzzled as to why my Vuex modules are not functioning properly. I keep receiving the error message: "[vuex]

I've been searching for hours and can't figure out why I keep getting this error message: [vuex] unknown mutation type: groceryStore/getStoreApple on all of the commits to the mutations in the groceryStore-module. I believe I'm following the ...

Creating session variables in Joomla using checkboxes and AJAX

I'm currently working on implementing session variables in Joomla with AJAX when checkboxes are selected. Below is the code snippet from select_thumb.ajax.php file: $_SESSION['ss'] = $value; $response = $_SESSION['ss']; echo ...

Testing Vue Components - Simulating the return value of a plugin

I have a unique scenario where I need to mock the return value of a custom plugin without importing it directly into my test. By creating a mock function for the plugin, I can easily achieve this goal. However, I am unsure how to change the return value of ...

Navigating the Angular Controller life cycle

I have set up my application states using ui-router: $stateProvider .state('app', { abstract: true, views: { 'nav@': { templateUrl: 'app/navbar.html', controller: 'NavbarController' ...

Searching for a specific word within a given string using a loop

Currently, I'm developing a 'for' loop to search for my name, Andrew, in a given text and store the occurrences in an array. However, there seems to be an issue with the implementation. /*jshint multistr:true */ var text = ("Andrew is real ...

Unable to access the value of an undefined property

In my HTML view, I have the following code: <form name="adduser" id="signupForm" novalidate> <span>First Name</span> <label class="item item-input" id="profileLabel"> <input id="profileInput" type="text" ...

Attempting to utilize ng-click on an element that has been added using element.append() in the postlink phase?

I have been working on customizing a particular angular library to incorporate some new features. https://github.com/southdesign/angular-coverflow/blob/master/coverflow.js As part of this process, I am looking to attach click events to the elements being g ...

What is the best way to deselect all "md-checkboxes" (not actual checkboxes) on an HTML page using a Greasemonkey script?

After spending a frustrating amount of time trying to disable the annoying "md-checkboxes" on a certain food store website, despite unchecking them multiple times and reporting the issue without any luck, I have come to seek assistance from knowledgeable e ...

What is the most effective way to organize an array according to a key function that is computationally intensive?

After posting this question regarding sorting an array with a key function, it became evident that utilizing a comparison function was inevitable. The challenge at hand includes: Having a resource-intensive key function that needs to be transformed into ...