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

Explore Python and Selenium for implementing pagination with JavaScript functionality

Having recently started using Selenium with Python 2.7, I am looking to click on certain JavaScript elements used for pagination on a website. To provide context, here is the link to the page: . Any guidance or example code would be greatly appreciated. ...

Tips for preventing a function from being triggered twice during a state change

I'm currently working with a react component that looks like this: const [filter, setFilter] = useState(valueFromProps); const [value, setValue] = useState(valueFromProps); const initialRender = useRef(true); useEffect(() => { if (initialRender. ...

Using jquery ajax during the initial page load and then making another ajax call after 5 minutes eventually causes the browser to crash

I've been attempting to perform an ajax call when the page loads, and then every 5 minutes afterwards. Initially, this works fine, but after some time, it appears that ajax is being called multiple times simultaneously, causing my browser to crash. Up ...

When utilised within the same function, JSON values in JavaScript can yield varying results

Recently, I've been grappling with a JavaScript issue that involves fetching JSON values as data-attributes to populate a modal. This task sounds simple enough, but as a newcomer to this field, I find myself facing challenges. The main goal is to ite ...

An array filled with unique and non-repeating elements

I want to display random country flags next to each other, making sure they do not match. However, my specific case requires a unique solution for dealing with arrays: function displayRandomFlags() { var flagurls = ["ZPlo8tpmp/chi","cJBo8tpk6/sov","QyLo ...

do not continue loop if promise is rejected in AngularJS

I've attempted multiple methods, but still haven't found a solution to this issue. Within my code, there is a method called iterator that returns a promise; this method runs in a loop x number of times. If the iterator function returns a rejecte ...

At times, MomentJS may miscalculate and add an incorrect number of hours

My goal is to add a specific amount of hours to a 24-hour time, but I'm encountering an issue with the time 00:00. The code I've written works correctly for all times except midnight. For example, if I have 01:30 and add 1 hour, it gives me 02:3 ...

Updating the $location variable from the $rootScope perspective

I am facing an issue with my web app which is built using AngularJS. I have two functions in my code - one declared on the $rootScope and the other on the $scope. The code snippets are shown below: app.js app.run(function ($rootScope, $location) { $roo ...

Node.js MySQL REST API query fails to execute

I am developing a login/sign up API using nodejs, express, and mysql. Despite receiving the "Successful Sign Up!" message without any errors during testing, the user table in the database remains empty. Below is the query I am attempting to execute: con. ...

Switch between showing the Font Awesome TitleText and its associated Class with a single click

Can the value of the title attribute for <i> be toggled? For example, if the title is set to <i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true"> within <div class="postoption"> I would like to toggle both the title te ...

adding content to div is becoming less speedy

Currently, I'm developing a drawing board using only html/css/jquery and the drawing functionality is working smoothly. The approach I've taken involves capturing the mousemove events and placing a dot (div) at each point where the event occurs, ...

Please provide the date using the Foundation Datepicker tool

Beginner in JavaScript here! I am having an issue with submitting dates selected using the Foundation Datepicker from . I have searched for solutions on StackOverflow like Post form on select with JQuery Datepick, but none seem to work in my case. If a Ja ...

Encountering an unspecified value in the JSON response

Currently, I am using the CodeIgniter shopping cart feature to fetch all the "add to cart" information. The issue arises when I try to access the quantity (o.qty) from the alerted data. It seems to return as undefined. $(document).ready(function() { ...

The SecurityError known as DOM Exception 18 can be triggered when attempting to use Backbone fetch with a datatype of "xml"

Encountering an error while attempting to fetch an "xml" response using backbone. My fetch code: itenary.fetch({ data :{date:dayFormatToSend.toString(), advisorId:"0000222186"}, dataType:"xml", success:function(response){ console.log(response); } ...

How can I get electron to interact with sqlite3 databases?

I've exhausted all my options and still can't get it to function. This error message keeps popping up: https://i.stack.imgur.com/D5Oyn.png { "name": "test", "version": "1.0.0", "description": "test", "main": "main.js", "scripts": { ...

Instantaneous results are not achievable with AJAX

I'm struggling to create a live keyword search box using AJAX in my code. Currently, I have to hit ENTER on the keyboard for it to perform the search. Ideally, I want the results to update as I type without having to press ENTER. Here is an example o ...

Avoiding the use of if statements in Javascript

I've recently started learning Javascript and I'm facing an issue with my code. I want to create a functionality where clicking on an image on one page redirects you to another page and shows a specific div based on the clicked image. To achieve ...

Enhance the fields on a spring form by incorporating new elements upon the click of a button

I am working with a class named Student that looks like this: public class Student { private String firstName; private String lastName; private BigDecimal balance; private List<Option> options; ... } Here is the form I am using: <form:for ...

Angular Datepicker MinDate function prevents selection of dates "behind" by one

I've encountered an issue with the Angular Bootstrap Datepicker where I'm setting the min-date attribute as follows: <input type="text" class="" uib-datepicker-popup="MM/dd/yyyy" show-button-bar="false" ng-model="vm.date" ng-change= ...

Uncovering the Solution: Digging into a Nested ng-repeat to Access an Array in AngularJS

I am working with a recursive array in JavaScript: [{ type: 'cond', conditionId: 1, conditions: undefined }, { type: 'cond', conditionId: 2, conditions: undefined }, { type: 'group', conditionId: undefined, ...