Michael Andrew Michael Andrew - 1 month ago 5
PHP Question

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

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

The_Controller.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 cause data not fill by return value of postSomething function inside CI_Controller so it always false. How to get return value/data from CI_Controller to AJAX?

Thank you

Answer

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.

Comments