I just started learning using AJAX with Codeigniter. On my view, I have a textarea and a button which uses AJAX to submit the text in the textarea to my controller, which retrieves data from the database and returns this data to the view. However I am getting the error "disallowed key characters" in the callback function. This happens even when I simply echo
a string. What is happening?
Btw, should I use return $result
or echo $result
in the controller to pass the data back to the webpage?
AJAX
$(function() {
$("#search_button").click(function(e){
e.preventDefault();
var search_location = $("#search_location").val();
$.get('index.php/main/get_places', search_location, function(data){
$("#result").html(data);
console.log(data);
});
});
});
Controller
function get_places($address) {
$search_latlng = $this->geocode_address($address);
$this->load->model('main_model.php');
$result = $this->main_model->get_places($search_latlng);
echo "test";
}
CodeIgniter has restricted the characters in the url to:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; //Inside config.php
Chances are you are putting in characters that not in this list in the address when you send the AJAX request. My suggestion would be change the $.get
to $.post
and then get the post data out in the controller. Something like this:
AJAX
$(function() {
$("#search_button").click(function(e){
e.preventDefault();
var search_location = $("#search_location").val();
$.post('index.php/main/get_places', {'search_location': search_location}, function(data){
$("#result").html(data);
console.log(data);
});
});
});
Controller
function get_places() {
$address = $this->input->post('search_location');
$search_latlng = $this->geocode_address($address);
$this->load->model('main_model.php');
$result = $this->main_model->get_places($search_latlng);
echo $result;
}
As for the echo
vs return
, use echo
.
You're probably not allowing querystrings in your URL and the Ajax function adds querystring to the url. Take a look at the following url to learn how to turn querystrings on:
http://www.askaboutphp.com/58/codeigniter-mixing-segment-based-url-with-querystrings.html