CodeIgniter - How to return values ββfrom ajax method?
I am trying to pass a date to an ajax function and get the appropriate type and title according to that date separately from the database.
I used the following Model .
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 the 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 View, I want to get the title and type separately for a specific day. I used the following ajax function. But I don't know how to return values ββfrom ajax function and how to intercept 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 of great help if anyone give me an idea.
+3
source to share
3 answers
In the 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;
}
});
0
source to share
Send any JSON data 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);
}
0
source to share