I’m having an issue with Codeigniter with the following symptoms.
- When I send the data to the controller, I am unable to capture the POST data.
- I’ve tried to echoed a simple word so I could return it back to the AJAX call and the responses are always null.
- Since I am unable to capture the data in the controller, I cannot send it to the model which also returns null back to the controller.
I feel a little lost with this one.
Here’s the sample code for the AJAX request. When I do this, I am able to see in the browser console that the "id" value is indeed being POST (id : 1).
var id = 1; //a simple test value to send to the ajaxtest function in the user controller.
$.ajax({
type : 'POST',
url : '<?php echo base_url('user/ajaxtest'); ?>',
data : {id : id},
cache : false,
success: function(res){
var h = 'Another Test'; //just a test to add to the console.log along with the response.
console.log({res, h});
}
});
in the controller I defined the following function.
function ajaxtest() {
//$res = $this->input->post('id');
$res = $this->test_model->ajaxtest2();
echo $res;
}
Now, before I get into the model, here’s something else I’ve tried in the controller just to test the AJAX request.
//Tried to capture the POST value and echo back to the AJAX response but it goes back null.
function ajaxtest() {
$res = $this->input->post('id');
//$res = $this->test_model->ajaxtest2();
echo $res;
}
//Tried to send a value, still null ajax response.
function ajaxtest() {
$res = '1';
echo $res;
}
function ajaxtest() {
//$res = '1';
echo '1';
}
In the MODEL, I created this simple function (which is not working because for some reason I can’t capture the ID value or send anything back to AJAX).
function ajaxtest2() {
$res = $this->input->post('id');
return $res;
}
I also tried returning a simple value and it doesn’t do a thing.
function ajaxtest2() {
$res = '1';
return $res;
}
If anyone could shed some light, it would be greatly appreciated.
Thanks in advance.
3
Answers
Please add an option in your ajax call because you are trying to send JSON data.
dataType: 'json',
That’s your final call will be like the following:
They have many way to test this :
.error()
function in your ajax call?dataType
sended by ajax option :dataType: 'json'
ordataType: 'jsonp'
print_r($_REQUEST)
into your controller to saw Request elements passed into POSTid
try to print$this->input->post('id')
Check https://api.jquery.com/jquery.ajax/ for all reference functions and parameters
Try these elements and let us know if everything is working fine.
Just a note for jQuery :
When you pass data through ajax, it must be in Object type.Like, {‘id’ : id}.But in your code, you have given, {id : id}. Hope you understood the bug.