Reputation: 161
I am trying to pass a date into an ajax function and get the relevant type and title according to that date separately from the database.
I have used the following Model function.
function get_reservation_for_add_popup($date_cal) {
$this->db->select('reservations.title,reservations.type');
$this->db->from('reservations');
$this->db->where('reservations.date_cal', $date_cal);
$this->db->where('reservations.is_deleted', '0');
$query = $this->db->get();
return $query->result();
}
My Controller function is like following
function get_title_and_type() {
$reservation_service = new Reservation_service();
$data['reservation_pop_up'] = $reservation_service->get_reservation_for_add_popup($this->input->post('date', TRUE));
echo $data;
}
In the View I want to get title and the type separately for the particular day. I used the following ajax function. But i don't know how to return values from an ajax function and how to catch them into variables.
var date = $('#date').val();
var title=[];
var type=[];
$.ajax({
type: 'POST',
url: '<?php echo site_url(); ?>/dashboard/get_title_and_type',
data: 'date=' + date,
success: function(msg) {
return msg;
}
});
Since i am very new to ajax it will be a great help if someone give me an idea.
Upvotes: 4
Views: 3363
Reputation: 18600
In ajax Change following
data: 'date=' + date,
TO
data: {'date' : date},
Upvotes: 3
Reputation: 2588
In controller
function get_title_and_type() {
$reservation_service = new Reservation_service();
$data['reservation_pop_up'] = $reservation_service->get_reservation_for_add_popup($this->input->post('date', TRUE));
echo json_encode($data);
}
In your ajax add dataType json
var date = $('#date').val();
var title=[];
var type=[];
$.ajax({
type: 'POST',
dataType: 'json',
url: '<?php echo site_url(); ?>/dashboard/get_title_and_type',
data: {'date' : date},
success: function(msg) {
return msg;
}
});
Upvotes: 1
Reputation: 21231
Send any kind of data JSON encoded from your PHP file
function get_title_and_type() {
..... your code here
$data['test_msg_2'] = "Hello 1";
$data['test_msg_2'] = "Hello 2";
echo json_encode($data);
}
And in your JS
$.ajax({
type: 'GET',
url: '<?php echo site_url(); ?>/dashboard/get_title_and_type',
data: 'date=' + date,
success: function(msg) {
msg = $.parseJSON(msg);
console.log(msg.reservation_pop_up);
console.log(msg.test_msg_2);
console.log(msg.test_msg_2);
}
Upvotes: 1