phpajaxcodeigniter

How to send/return data/value from CI_Controller to AJAX


As the title, I want the CI_Controller to return value/data back to AJAX which gives the request before.

The_Controller.php

<?php

class The_Controller extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    function postSomething()
    {
        $isHungry = true;
        if(isHunry){
            return true;
        }else{
            return false;
        }
    }

}

AJAX

$(document).ready(function() {

        $('#form').on('submit', function (e)
        {
            e.preventDefault(); // prevent page reload
            $.ajax ({
                type : 'POST', // hide URL
                url : '/index.php/The_Controller/postSomething',
                data : $('#form').serialize (),
                success : function (data)
                {
                    if(data == true)
                    {
                        alert ('He is hungry');
                    }
                    else
                    {
                        alert ('He is not hungry');
                    }       
                }
                , error: function(xhr, status, error)
                {
                    alert(status+" "+error);
                }
            });
            e.preventDefault();
            return true;
        });
    });

The Problem :

The AJAX code above always get FALSE for variable data. It's not get return value from postSomething function inside CI_Controller.

The Question:

I want to if(data == true) result alert ('He is hungry');, but because data not filled by return value of postSomethingfunction insideCI_Controllerso it always false. **How to get return value/data fromCI_Controller` to AJAX?**


Solution

  • you need to change your code a little bit. no need to return data, just echo true or echo false from your controller. Hope you will get your desired result.