I am trying to develop a search function in php using codeigniter framework. It should be able to search using the time and the hall too. it works when i use only the time.But it gets very wrong when i use hall.following i have attached all the codes i am using.
I have divided Model into two sections like model and service. in the model there are getters and setters.In the service class only i am writing querys.if anyone can give me a positive answer that would be very helpful. Thanks in advance.
Model(reservation_service.php)
function search_reservations($time,$hall) {
$this->db->select('reservations.*');
$this->db->from('reservations');
$this->db->like('time', $time);
$this->db->or_like('hall',$hall);
$this->db->where('is_deleted', '0');
$query = $this->db->get();
return $query->result();
}
Controller(dashboard.php)
function search_results() {
$reservation_service = new Reservation_service();
$time_booking = trim($this->input->post('time', TRUE));
$hall_booking = trim($this->input->post('hall', TRUE));
$data['search_results'] = $reservation_service->search_reservations($time_booking,$hall_booking);
$partials = array('content' => 'dashboard/search_results');
$this->template->load('template/main_template', $partials, $data);
}
function search_reservations() {
$reservation_service = new Reservation_service();
$data['search_results'] = $reservation_service->search_reservations(trim($this->input->post('time', TRUE)));
$partials = array('content' => 'dashboard/reservation_report');
$this->template->load('template/main_template', $partials, $data);
}
view
reservation_report.php
<div class="form-group"><br>
<input id="time" name="time" type="text" placeholder="Time Slot">
<input id="hall" name="hall" type="text" placeholder="Hall">
<button class="btn btn-primary" onclick="search()" >Search</button>
</div>
<div id="search_results">
<?php echo $this->load->view('dashboard/search_results'); ?>
</div>
<script type="text/javascript">
function search() {
var time = $('#time').val();
$.ajax({
type: "POST",
url: '<?php echo site_url(); ?>/dashboard/search_results',
data: "time=" + time,
success: function(msg) {
$('#search_results').html(msg);
}
});
}
</script>
search_results.php
<div class="adv-table">
<table class="display table table-bordered table-striped" id="bookings_table">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Hall</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($search_results as $result) {
?>
<tr id="bookings_<?php echo $result->id; ?>">
<td><?php echo ++$i; ?></td>
<td><?php echo $result->date; ?></td>
<td><?php echo $result->hall; ?></td>
<td><?php echo $result->time; ?></td>
<?php } ?>
</tbody>
</table>
</div>
Problem is with ajax function here you are not sending the value of hall variable in post
<script type="text/javascript">
function search() {
var time = $('#time').val();
var hall = $('#hall').val();// add this to your code
$.ajax({
type: "POST",
url: '<?php echo site_url(); ?>/dashboard/search_results',
data: {time:time,hall:hall},//pass parameter
success: function(msg) {
$('#search_results').html(msg);
}
});
}
</script>
Your code seems to be wrong when loading model in dashboard.php:
$reservation_service = new Reservation_service();
Try to load your model object as described in CodeIgniter Documentations:
$this->load->model('reservation_service');
therefore your dashboard.php should be like this:
function search_results() {
$this->load->model('reservation_service');
$time_booking = trim($this->input->post('time', TRUE));
$hall_booking = trim($this->input->post('hall', TRUE));
$data['search_results'] = $this->reservation_service->search_reservations($time_booking,$hall_booking);
$partials = array('content' => 'dashboard/search_results');
$this->template->load('template/main_template', $partials, $data);
}
function search_reservations() {
$this->load->model('reservation_service');
$data['search_results'] = $this->reservation_service->search_reservations(trim($this->input->post('time', TRUE)));
$partials = array('content' => 'dashboard/reservation_report');
$this->template->load('template/main_template', $partials, $data);
}
Related
I am new on codeigniter I tried to fetch data which is filter by date from database and display it in my view page through ajax without refreshing my page.
I tried lot but didn't get the solution .
Here is my controller:
public function sohan_by_date(){
/* Check the validation of search by date function*/
$this->form_validation->set_rules('start_date', 'Start Date', 'trim|required');
$this->form_validation->set_rules('end_date', 'End Date', 'trim|required');
if($this->form_validation->run()){
/* display data from database from comparing the date in database*/
$date1=$this->input->post('start_date');
$date2=$this->input->post('end_date');
$start_date=date('Y-m-d', strtotime($date1));
$end_date=date('Y-m-d', strtotime($date2));
$check=$this->task->get_by_date_sohan($start_date,$end_date);
if($check){
$data['result']=$this->task->get_by_date_sohan($start_date,$end_date);
$this->load->view('admin/sohan_task_by_date', $data);
return json_encode($data);
}
else{
redirect('task/sohan_task');
}
}
else{
redirect('task/sohan_task');
}
}
Here is my model:
public function get_by_date_sohan($start_date,$end_date){
/* This display all task of sohan from database by date*/
$this->db->select('*');
$this->db->from('task_form');
$this->db->where('name','sohan');
$this->db->where('date >= ',$start_date);
$this->db->where('date <= ',$end_date);
$query=$this->db->get();
return $result=$query->result();
}
Here is my ajax:
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url();?>task/sohan_by_date",
dataType: "json",
success: function(data){
debugger;
$('#result_table').html(data);
},
error: function() { alert("oops..."); }
});
});
</script>
here is my view:
<div class="form-body">
<div data-example-id="simple-form-inline">
<?php
$attributes = array('class' => 'form-inline');
echo form_open('', $attributes);
?>
<div class="form-group">
<input type="text" class="form-control" name="start_date" id="start_date" placeholder="Start Date" >
</div>
<div class="form-group">
<input type="text" class="form-control" name="end_date" id="end_date" placeholder="End Date">
</div>
<button type="submit" class="btn btn-default" id="getdata">Check</button>
<?php
echo form_close();
?>
</div>
</div>
<div id='result_table'>
<?php include('date.php');?>
</div>
My date.php file is:
<table class="table table-striped table-hover table-responsive">
<thead>
<tr class="success">
<th>Name</th>
<th>Date</th>
<th>Work</th>
<th>Partner</th>
<th>Director</th>
<th>Time</th>
<th>Task</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php foreach($result as $row) { ?>
<tr>
<td><?php echo $row->name;?></td>
<td><?php echo $row->date;?></td>
<td><?php echo $row->work;?></td>
<td><?php echo $row->partner;?></td>
<td><?php echo $row->director;?></td>
<td><?php echo $row->time;?></td>
<td><?php echo $row->task;?></td>
<td><?php echo $row->status;?></td>
</tr>
<?php } ?>
</tbody>
</table>
When I am fetching data normally without any using ajax and display in view then it working properly but page is refreshing.It means my controller and my model is working properly.But when I used ajax to display data without refreshing page then its not working ..please help me to find the solution .I dont have much more knowledge in ajax.
I got the Answer now its working perfectly. here i am going to share my answer.
Here is Jquery:
$('#myform').submit(function (event) {
dataString = $("#myform").serialize();
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>task/sohan_by_date",
data:dataString,
success:function (data) {
$('#task').html(data);
}
});
event.preventDefault();
});
Here is my controller:
public function sohan_by_date(){
/* Check the validation of search by date function*/
$this->form_validation->set_rules('start_date', 'Start Date', 'trim|required');
$this->form_validation->set_rules('end_date', 'End Date', 'trim|required');
if($this->form_validation->run()){
/* display data from database from comparing the date in database*/
$date1=$this->input->post('start_date');
$date2=$this->input->post('end_date');
$start_date=date('Y-m-d', strtotime($date1));
$end_date=date('Y-m-d', strtotime($date2));
$check=$this->task->get_by_date_sohan($start_date,$end_date);
if($check){
$data['result']=$this->task->get_by_date_sohan($start_date,$end_date);
$this->load->view('admin/date', $data);
return json_encode($data);
}
else{
redirect('task/sohan_task');
}
}
else{
redirect('task/sohan_task');
}
}
Here is a form in view:
<?php
$attributes = array('class' => 'form-inline','id'=>'myform');
echo form_open('', $attributes);
?>
My all code in details I already explain in my question if any one got stuck like this problem please compare my above question and my this answer.
Thank you
First give an id attribute to ua form.It is not necessary, you can get data by class also.But it might be a good practice.
<?php
$attributes = array('class' => 'form-inline','id'=>'myform');
echo form_open('', $attributes);
?>
Now in ua clicks,get the form variables by form.serialize method in ajax.
var str =$('#myform').serialize();
$.ajax({
url: '<?php echo site_url('task/sohan_by_date'); ?>',
async: false,
type: 'POST',
data:str,
dataType: 'html',
success: function(data)
{
alert(data);
},
error:function(error)
{
alert(error)
}
});
Now change ua controller code as:
if($check)
{
$this->task->get_by_date_sohan($start_date,$end_date);
}
if ua getting the data in alert as array,use json.stringify() to alert the data.. Good luck.
I wanted to pass ID of each row from table and pass it to controller using AJAX and wanted to update the Dropdown Selection of that row in DB.
The Selection what i make in Dropdown is passed to the controller but not sure how to update in DB based on its each row condition. A help would be much Appreciated!!!
Below is the Screenshot of my UI
Screen Shot with ID and Dropdown
View File
<?php if( is_array( $fbrecords ) && count( $fbrecords ) > 0 )
foreach($fbrecords as $r) { ?>
<tr class="idrow">
<td id="tdname" ><!-- style="display:none;" --> <?php echo $r->id; ?></td>
<td><?php echo $r->fullname; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->mobile; ?></td>
<td><?php echo $r->message; ?></td>
<td><?php echo $r->jtime; ?></td>
<td> <?php $data=array(
'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'
);
$data_status = array(
'none' => 'none',
'A&A' => 'Attended & Acted',
'YTA' => 'Yet to Attend',
);
echo form_dropdown($data, $data_status, set_value('status')); ?> </td>
<td><button type="button" class="btn btn-sm btn-success emlbtn" > Reply to <?php $fname=explode(" ",$r->fullname); echo $fname[0]; ?></button>
AJAX Code
$(document).ready( function() {
$(".statusClass").change(function(event) {
event.preventDefault();
//var dropDown = document.getElementById("status");
//var status = dropDown.options[dropDown.selectedIndex].value;
var status = $(this).val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit",
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}
});
});
});
Controller
public function user_data_status_submit(){
$data = array(
'status' => $this->input->post('status'),
'id'
);
//Either you can print value or you can send value to database
echo json_encode($data);
$this->login_database->feedback_update($data);
}
Update Function in Model
public function feedback_update($data){
$this->db->set($data);
$this->db->where("id", $old_id);
$this->db->update('feedback_table', $data);
}
First change your $data array() like this :
$data = array(
'data-user' => $r->id, //ID of the row
'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'
);
Your ajax should be like this way:
$(".statusClass").each(function(index, element) {
$(this).on('change', function(e) {
var id = $(this).data('user');
var status = $(this).val();
console.log(id);
console.log(status);
// your ajax stuff go as usual
});
});
Based on the question, I come up with this simple solution. To be able to get the id and pass it yo your ajax call, all you need is add data-id for example inside your <td> tag.
Take a closer look below
<td id="tdname" data-id="<?php echo $r->id ?>" ><?php echo $r->id; ?></td>
Now that we have the id value inside our data-id, we can now pass it using jquery like below
$(document).ready( function() {
$(".statusClass").change(function(event) {
event.preventDefault();
var id = $("#tdname").data("id");
var status = $(this).val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit/" + id,
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}
});
});
});
Lastly, add the $id param inside your controller.
I want my second selects options to vary depending on the choice in the first select.
If you pick "Skalman" you can't pick "Whole day with lunch" and if you choose "Lilleskutt" you can't choose "Half day".
I haven't worked with AJAX before but thinking that it might be the right way to go, if anyone could help me out I would be more than grateful!
I get the options from the database, using two functions in Booking.php:
private function get_room_options() {
$this->load->model('Booking_Model');
$rooms = $this->Booking_Model->get();
$rooms_form_options = array();
// get room title and store in array
foreach ($rooms as $id => $room) {
$rooms_form_options[$id] = $room->title;
}
return array(
'rooms_form_options' => $rooms_form_options,
);
}
public function get_package_options() {
$room = $this->input->post('searchData');
$this->load->model('Package_Model');
$packages = $this->Package_Model->get();
$packages_form_options = array();
foreach ($packages as $id => $package) {
$packages_form_options[$id] = $package->package_name;
}
return array(
'packages_form_options' => $packages_form_options,
);
}
And in my booking.php you find the form:
<?php
echo form_open('booking/preview') ?>
<div>
<?php echo form_label('Conference Room: ', 'id') ; ?>
<?php echo form_dropdown('id', $rooms_form_options, set_value('id')); ?>
</div>
<div>
<?php echo form_label('Package type: ', 'package_id') ; ?>
<?php echo form_dropdown('package_id', $packages_form_options, set_value('package_id')); ?>
</div>
<div>
<?php echo form_label('Number of Participants: ', 'number_people') ; ?>
<?php echo form_input('number_people', set_value('number_people')) ; ?>
</div>
<div>
<?php echo form_submit('preview', 'Book'); ?>
</div>
<?php echo form_close(); ?>
And my script so far:
<script type="text/javascript">
$(function() {
$(document).on('change', '[name=id]', function(e){
var searchData = $(this).val();
$.ajax({
url: "<?php echo base_url('index.php/booking/get_package_options'); ?>",
type: 'POST',
data: searchData,
success: function() {
// how should I get the options in here?
}
});
});
});
</script>
CodeIgniter doesn't support ajax.For more clarification http://phpframeworks.com/
So lets start from view
<?php echo form_open('booking/preview') ?>
<div>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<?php echo form_label('Conference Room: ', 'id'), form_dropdown('id', $rooms_form_options, set_value('id')) ?>
</div>
<div>
<?php echo form_label('Package type: ', 'package_id'), form_dropdown('package_id', $packages_form_options, set_value('package_id')) ?>
</div>
<div>
<?php echo form_label('Number of Participants: ', 'number_people'), form_input('number_people', set_value('number_people')) ?>
</div>
<div>
<?php echo form_submit('preview', 'Book') ?>
</div>
<?php echo form_close() ?>
Here optimize your code by removing trailing semicolon & multiple echo
into single statement.
Now in your js part
$(function() {
$(document).on('change', '[name=id]', function(e){
var searchData = $(this).val();
$.post('YOUR_SEARCH_URL', { data : searchData }).done(function(data, textStatus, jqXHR) {
var h = '';
$(data.YOUR_SERVER_RESPONSE_KEY).each(function(i, v){
h += '<option value="' + i + '">' + v + '</option>'
});
$('[name=package_id]' ).html(h);
}).error(function(jqXHR, textStatus, errorThrown) {
//Handle your ajax error
});
});
});
Now at your controller
public function YOUR_CONTROLLER_ACTION() {
$data = $this->input->post('data');
//Do your work & get data from model for the id
//now send json response
return $this->output
->set_content_type('application/json')
->set_output(json_encode(YOUR_JSON_RESPONSE_ARRAY));
}
Check this two links http://code.runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php & http://code.tutsplus.com/tutorials/codeigniter-from-scratch-day-8-ajax--net-9243 for more details
When using jQuery AJAX in cakePHP 1.3, the AJAX response includes the full layout rather than just the array with dataset from the model. How to I prevent this whole page from being rendered? I have tried to use $this->autoRender = false; and $this->layout = 'ajax', but this did not solve the problem. It actaully produced no response in the returned data.
My controller action is:
public function search() {
if (empty($this->data)) {
} else {
// $this->autoRender = false;
// $this->layout = 'ajax';
$request = $this->data;
$this->set('data', $this->Event->search($request['Event']['search']), 'host');
}
}
And my view is:
<!-- app/views/events/search.ctp -->
<h1>Corporate Events</h1>
<form method="post" action="search">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
<p><?php echo $html->link("Add Event", "/events/add"); ?>
<table>
<tr>
<th style='width:100px'>Id</th>
<th style='width:100px'>Title</th>
<th style='width:100px'>Host</th>
<th style='width:100px'>Description</th>
<th style='width:100px'>Action</th>
</tr>
<div id= "results"></div>
<?php foreach ($data as $event): ?>
<tr>
<td><?php echo $event['id']; ?></td>
<td>
<?php echo $html->link($event['event_title'],'/events/view/'.$event['id']);?>
</td>
<td><?php echo $event['host']; ?></td>
<td><?php echo $event['description']; ?></td>
<td>
<?php echo $html->link(
'Delete',
"/events/delete/{$event['id']}",
null,
'Are you sure?'
)?>
<?php echo $html->link('Edit', '/events/edit/'.$event['id']);?>
</td>
</tr>
<?php endforeach; ?>
</table>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var searchString = $("#search_box").val();
var data = {'data[Event][search]':searchString};
if(searchString) {
$.ajax({
type: "POST",
url: "/events/search",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
Thanks!
I don't understand your question well, but this will help you with displaying to your view without the layout being echoed wholly.
Put this on the javascript inside the view,
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var searchString = $("#search_box").val();
if(searchString) {
$.ajax({
url: "/events/search/" + searchString,
beforeSend: function() { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(data){ // this happens after we get results
$("#results").show();
$("#results").append(data);
}
});
}
return false;
});
});
</script>
Then use the code below for your controller,
public function search($data=null) {
$this->autoRender = false;
//your code here;
return $data;
}
I would recommend having another function do the results and rendering them. Make a function called update_results. Following examples assumes you have request handler and jquery in place.
Simple Example:
//Controller
function search()
{
//search filters
$locations = $this->Event->Location->find('list',array('order'=>'Location.name'));
//set vars for view
$this->set(compact( 'locations'));
}//search
function update_results()
{
//location filter
if(!empty($this->data['Event']['location_id']))
$conditions['Event.location_id']=$this->data['Event']['location_id'];
$results=$this->Event->find('all',array('conditions'=>$conditions,'limit'=>15));
//debug($conditions);
$this->set('results',$results);
}//update result
//Views
//search.ctp
<?php echo $form->create('Event',array('action'=>'search'));
echo $this->Form->input('Event.location_id', array('label'=>'Location','empty'=>TRUE));
echo $js->submit('Find Trainings', array('update' => '#trainingresults','url'=> array('controller'=>'events', 'action'=>'update_results')));
echo $form->end(); ?>
<?php
echo $html->div('trainingresults',null,array('id'=>'trainingresults'));
echo '</div>';
?>
//update_results.ctp
<?php
$timestamp=date('r');
echo "<h4>Search Results ($timestamp)</h4><br/>";
if(empty($results))
{
echo "<p class='well'><strong>No Trainings found. Try different search criteria.</strong></p>";
}
else
{
foreach($results as $display)
{
//Event Info
$location=$display['Location']['name'];
echo $location;
}//for
}//else
?>
I am developing a simple students information application. I have student list in my index.phtml and I can edit student information form there. It's working nice but I want to use modal for edition student info. But I don't know how to do this.Below I have posted my current codes :
/// indexController.php
public function editAction()
{
$modelStudents = new Application_Model_DbTable_Students();
$id = (int) $this->_getParam('id');
$student = $modelStudents->fetch($id);
$form = new Application_Form_Student($student->email);
$form->submit->setLabel('Save');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$id = (int)$form->getValue('id');
$name = $form->getValue('name');
$email = $form->getValue('email');
$phone = $form->getValue('phone');
$students = new Application_Model_DbTable_Students();
$students->updateStudent($id, $name, $email, $phone);
$this->_helper->redirector('index');
} else {
$form->populate($formData);
}
} else {
$id = $this->_getParam('id', 0);
if ($id > 0) {
$form->populate($modelStudents->getStudent($id));
}
}
}
/// index.phtml
<html>
<head>
<style type="text/css" rel="stylesheet">
</style>
<script type="text/javascript" src="jQuery.js"> </script>
<script type ="text/javascript" src="jquery.simplemodal-1.4.2.js" ></script>
<script>
<?php
echo "Student List";
?>
<p><a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'add'));?>">Add new student</a></p>
<table border="1">
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
<?php foreach($this->students as $student) : ?>
<tr>
<td><?php echo $student->name;?></td>
<td><?php echo $student->email;?></td>
<td><?php echo $student->phone;?></td>
<td>
<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'edit', 'id'=>$student->id));?>">Edit</a>
<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'delete', 'id'=>$student->id));?>">Delete</a>
<p id="delete" > Delete </p>
</td>
</tr>
<?php endforeach; ?>
</table>
</center>
</html>
////edit.phtml
<center>
<?php
echo "Edit Student List ";
echo $this->form ;
?>
</center>
Please let me know how to use jQuery simple modal plugin to preform this task.
Thanks in advance
Start by editing your index.phtml file to add a class and the student id to your edit link:
<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'edit', 'id'=>$student->id));?>" class="editBtn" studentId="<?=$student->id?>">Edit</a>
Then, in an included js file:
$(document).ready(function() {
$(function() {
//Event triggered when clicking on the edit btn
$('.editBtn').click(function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
//Get the page and add it to the modal
studentId = $(this).attr('studentId');
var data={};
data['id'] = studentId;
url = "/index/edit/";
$.get(url, data, function(resp) {
$.modal(resp);
});
});
});
});
This should help you get started...