Reputation: 33
I am new in codeigniter. I am writing a code. AJAX response is not returning.
Here is my controller:
public function getValue()
{
$this->load->helper('url');
$data = array(
'username' => $this->input->post('username'),
'email'=>$this->input->post('email'),
'address'=>$this->input->post('address')
);
echo json_encode($data);
die;
}
and it is view code:
$( document ).ready(function() {
$('#btn_submit').on("click", function(event){
event.preventDefault();
var username = $('#username').val();
var email = $('#email').val();
var address = $('#address').val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/MyApp/getValue",
dataType: 'json',
async:true,
crossDomain:true,
data: {username: username, email: email, address: address},
success: function ( data) {
console.log(data);
},
error: function ( data ) {
console.log('error');
}
});
});
});
I am new with codeigniter, so I don't know how to return response and work with AJAX. I have coded with the help of web but still getting errors. Please guide me how to fix this. Thanks
Upvotes: 0
Views: 1790
Reputation: 1394
Please try after setting content-type for the response like below.
header('Content-Type: application/json');
echo json_encode($data);
die;
Ajax response expects json data since your code set dataType: 'json'
Upvotes: 0
Reputation: 8964
Simple answer remove die;
from the getValue()
function.
Codeigniter does not actually output anything until after the controller finishes execution. The call to die;
short circuits the normal operation of the framework and so nothing gets output. In other words, echo json_encode($data);
never actually happens.
Upvotes: 1