Reputation: 3226
I'm not sure why this is not working
js - it alerts the width, sends it to the controller but it won't alert 'done'.
Network -> Preview (inspect element Chrome)
content: "<ul><li>50</li></ul>"
status: "ok"
$("#submit").click(function (e) {
e.preventDefault();
var width = $('#value').val();
$.ajax({
url: "http://domain.com/index.php/welcome/get_items",
data: {
width: width
}
}).done(function(data) {
$('div#cont').text(data);
}).fail(function() {
alert('Failed!')
});
});
controller
public function get_items()
{
$this->load->model('home_model');
$this->load->library('form_validation');
$this->form_validation->set_rules('width', 'Width', 'trim|required|xss_clean');
$width = $_GET['width'];
var_dump($width);
$one_exp = $this->home_model->one_exp($width);
var_dump($one_exp);
if($one_exp != false){
//$html = '<ul>';
foreach($one_exp as $exp) {
$html = $exp->width;
}
//$html .= '</ul>';
$result = array('status' => 'ok', 'content' => $html);
//header('Content-type: application/json');
echo json_encode($result);
exit();
}else{
$result = array('status' => 'no', 'content' => 'nothing here');
//header('Content-type: application/json');
echo json_encode($result);
exit();
}
}
home_model
function one_exp($width) {
$query_str = "SELECT * FROM files WHERE width=?";
$query = $this->db->query($query_str, array($width));
if($query->num_rows() > 0) {
foreach($query->result() as $item) {
$data[] = $item;
}
return $data;
} else {
return false;
}
}
Upvotes: 0
Views: 90
Reputation: 72885
What version of jQuery are you using? If you're using a later version, your syntax may simply not be working. You may also be encountering an Access-Control-Allow-Origin failure.
That said, try using jQuery 1.9.X or higher, and use the more verbose $.ajax
method:
$(document).ready(function () {
$("#click").click(function () {
var width = $('#width').val();
alert(width);
$.ajax({
url: "http://mywebsite.com/index.php/welcome/get_items",
data: {
width: width
}
}).done(function (data) {
alert(data);
}).fail(function() {
alert('Failed!')
});
});
});
See it in action here, and also the cross-origin failure is visible in the console log: http://jsfiddle.net/remus/LcTe4/
Don't forget to remove the echo
indicated in Ashok's answer, and you're best to add the json content type:
header('Content-type: application/json');
echo json_encode($result);
Upvotes: 1
Reputation: 163
in your contoller remove echo
public function get_items()
{
$this->load->model('home_model');
$width = $this->input->post('width');
$one_exp = $this->home_model->one_exp();
if ($one_exp != NULL)
{
$html = '<ul>'; //remove echo
foreach($one_exp as $exp)
{
$html .= '<li>';
$html .= $exp->width;
$html .= '</li>';
}
$html .= '</ul>';
$result = array('status' => 'ok', 'content' => $html);
echo json_encode($result);
exit();
}
else
{
$result = array('status' => 'no', 'content' => 'nothing here');
echo json_encode($result);
exit();
}
}
Upvotes: 2