Reputation: 453
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
Upvotes: 1
Views: 311
Reputation: 57
You have a typo in the PHP code
if(isHunry){
should be
if($isHungry){
Also, returning data to an AJAX request, you really should be sending the correct content type in the header. Ex.
header('Content-Type: application/json');
And print
or echo
the data, not return
it, as well as json_encode
it:
echo json_encode($data);
So your postSomething
php function should look something like this:
$isHungry = true;
header('Content-Type: application/json');
echo json_encode($isHungry);
Upvotes: 1
Reputation: 1231
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.
Upvotes: 1