Fetching post value via AJAX in Codeigniter views: A step-by-step guide

Having issues receiving Ajax response as it is coming back null.

The HTML layout includes:

<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
        <select class="form-control" class="form-control" id="choose_country">
                            <option value="">Select a prefered language</option>
                            <option value="en">EN</option>
                            <option value="fr">FR</option>
                            <option value="de">DE</option>
                            <option value="nl">NL</option>
                        </select>
                        </form>


<div id="table_load"></div>  <!-- loads search table -->

Javascript code snippet:

    <script>
    $('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');

          $("#choose_country").change(function(){
            var choose_country = $("#choose_country").val();
            $.ajax({
            url: "<?php echo base_url(); ?>admin/manage_article/search",
            type: "post",
            data: {choose_country: choose_country},
            dataType: 'json',
            async: false,
            success: function (response) {
                if(response.success == true){
alert('success');
            $('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');
                }else{
                    alert('fail');
                    }
            },
            });
          });
    </script>

Controller code:

public function search(){   

            $choose_language = $this->input->post('choose_country');    

            $this->load->view('admin/manage_article/search');

        }
    }

Goal is to send the select box value to the controller and display the selected value on the page $this->load->view('admin/manage_article/search');

Tried implementing the above code but keep getting "fail" in response alerts.

Still learning ajax, bear with any coding mistakes. Thank you!

Answer №1

Implement this code snippet in your controller:

public function search() {
    $language_chosen = $this->input->post('choose_country');
    $result = ($language_chosen) ? true : false;
    $this->output->set_content_type('application/json')->set_output(json_encode(array('choose_country' => $language_chosen, 'result' => $result)));
}

Your jQuery script should look like this:

<script type="text/javascript>
    $(document).ready(function() {
        $("#choose_country").change(function() {
            var choose_country = $("#choose_country").val();
            $.ajax({
                url: "<?php echo base_url(); ?>admin/manage_article/search",
                type: "post",
                data: {
                    choose_country: choose_country
                },
                dataType: 'json',
                async: false,
                success: function(response) {
                    if (response.result) {
                        alert('success');
                        $('#table_load').html(response.choose_country);
                    } else {
                        alert('fail');
                    }
                },
            });
        });
    });
</script>

If you are not utilizing business logic in the controller with AJAX, you can simply display the chosen country in the table_load element using the following script.

<script type="text/javascript>
    $(document).ready(function() {
        $("#choose_country").change(function() {
            var choose_country = $("#choose_country").val();
            $('#table_load').text(choose_country);
        });
    });
</script>

Answer №2

Avoid making multiple calls to the server - use AJAX for both fetching data and loading HTML content.

To load HTML content into the browser using AJAX, follow this JavaScript code snippet:

$("#choose_country").change(function () {
    var choose_country = $("#choose_country").val();
    $.ajax({
        url: "<?php echo base_url('admin/manage_article/search'); ?>",
        type: "post",
        data: {choose_country: choose_country},
        dataType: 'html', 
        success: function (response) {
            $('#table_load').html(response);
        },
        error: function(xhr, textStatus, errorThrown){
            console.log(textStatus, errorThrown);
        }
    });
});

Your controller logic seems correct, but ensure you handle the posted variable appropriately to get the desired language-specific HTML content.

If necessary, include a property named result in the returned JSON object for validation purposes:

public function search()
{
    $choose_language = $this->input->post('choose_country');

    $result = !empty($choose_language) ? true : false;

    $html = $this->load->view('admin/manage_article/search', NULL, TRUE);
    $out = array('result' => $result, 'html' => $html);
    $this->output
        ->set_content_type('application/json')
        ->set_status_header('200')
        ->set_output(json_encode($out));
}

In your success function, check for the result property before updating the HTML content:

success: function(response) {
    if (response.result === true) {
        alert('success');
        $('#table_load').html(response.html);
    } else {
        alert('fail');

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

The getStaticProps function will generate an object by fetching data from various URLs

Within my getStaticProps function in next js, I am faced with the challenge of fetching multiple dynamic URLs and exporting the results as props to the component. As these URLs are automatically generated, I do not know how many there will be to fetch. My ...

The backend post request is returning only "undefined" in JavaScript

Hey there, I'm still learning JS so please bear with me. I've been working on incrementing a value in a JSON file within my JS backend app. However, whenever I try to increase the associated value by the key, it ends up creating a new section la ...

Exploring Parameters to Customize Search Results in React

I am currently working on implementing a data filtering system based on user input. However, it seems that the data disappears whenever I enter something into the search box. Upon inspecting the dev tools, I can see that the query state is being saved pro ...

Finding strikeout text within <s> or <del> tags can be identified by closely examining the HTML codes

The issue arises with the text that reads as follows: 316.6.1 Structures. Structures shall not be constructed This is represented in HTML as: <b> <s> <span style='font-size:10.0pt'>316.6.1 Structures</span> ...

Bootstrap - Keeping track of the collapse state of <div> elements after page refresh

Looking for some guidance as a javascript/jquery beginner - I am utilizing Bootstrap along with data-toggle and collapse classes to display or hide divs. I have been searching online trying to find a solution that will maintain the state of all divs, wheth ...

Tips for verifying an alphanumeric email address

I need to create an email validation script that allows only alphanumeric characters. <script type = "text/javascript"> function checkField(email) { if (/[^0-9a-bA-B\s]/gi.test(email.value)) { alert ("Only alphanumeric characters and spaces are ...

The JavaScript code that added links to the mobile menu on smaller screens is no longer functioning properly

I recently created a website with a mobile navigation menu that should appear when the browser width is less than 1024px. However, I used some JavaScript (with jQuery) to include links to close the menu, but now the site is not displaying these links and t ...

Tips on saving checklist values as an array within an object using AngularJS

I need help with storing selected checklist items as an array in a separate object. I want to only store the names of the checklist items, but I am struggling to figure out how to achieve this. Below is the HTML code: <div ng-app="editorApp" ng-contro ...

The Angular UI Datepicker is not reflecting changes in scope variables within the dates-disabled function

I'm currently working with AngularJS and the Angular UI Bootstrap. I've encountered an issue that I initially thought was related to scope, then initialization, but now I'm stuck trying to figure out what's causing the problem. I' ...

For an unknown reason, I am facing difficulties in using the Storage feature from @angular/fire in ANGULAR 16

Recently I started exploring Angular/Fire and decided to test out some of its features by creating a basic app. Firestore and authentication were working smoothly, but when I attempted to include Storage, an error message popped up: ERROR FirebaseError: ...

Updating the style of different input elements using Angular's dynamic CSS properties

I am seeking guidance on the proper method for achieving a specific functionality. I have a set of buttons, and I would like the opacity of a button to increase when it is pressed. Here is the approach I have taken so far, but I have doubts about its eff ...

Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function. setSelectedSearchOptions(optionLabel: string) { //this.filterSection.reset(); this.selectedOption = optionLa ...

Tips for toggling the visibility of a <div> element with a click event, even when there is already a click event assigned

No matter what I try, nothing seems to be working for me. I'm looking to hide the <div id="disqus_thread"> at first and then reveal it when I click on the link "commenting", after the comments have loaded. This particular link is located at the ...

The user could not be deserialized from the session

I am having an issue with deleting users from my database. When a user is logged in and I try to refresh the page after deleting the user, I encounter the following error message: Error: Failed to deserialize user out of session Below is the code snippet ...

Ways to retrieve text like innerText that functions across all web browsers

I need to retrieve the text from a Twitter Follow button, like on https://twitter.com/Google/followers Using document.getElementsByClassName("user-actions-follow-button js-follow-btn follow-button")[0].innerText correctly displays the text as: Follow ...

What is the best way to retrieve user interaction data in Discord.js v13?

Is there a way to retrieve the activities from interaction.options? Whenever I try using interaction.options.getUser, I encounter this error message: cannot read properties of undefined (reading 'activities') Below is the snippet of my code: con ...

Tips for creating a new route within a separate component in React JS without causing the previous one to unmount

I am currently developing a recipe website using React JS and React Router. On the HomePage, I have set up a display of cards, each representing a preview of a recipe. Each card is enclosed within a <Link></link> tag. When one of these cards ...

Explore the latest update in the AngularJS single page application that introduces a new feature specifically designed for the initial login

Our AngularJS single page application has a new feature that we are ready to launch for customer use. We want to inform the logged in user about this new feature so they can start using it. We are looking for a small animated information symbol with a too ...

When my script is located in the head of the HTML page, I am unable to

My goal is to make my JavaScript code function properly when I insert it into either the head or body elements of an HTML document. Let's look at some examples: First, I insert the script into the body as shown in this example (works correctly): ...

Is there a way for me to display a customized error message using antd components?

During the registration process using React and Antd, if the backend returns the error message "user already registered" after clicking on "Sign up", it should be displayed in the form. You can customize the display as shown below: An example of how the u ...