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.
Related
i have two questions which are below;
1)How do i pass a value from a foreach to ajax. this is my code and what i have so far, tried putting the ajax inside the foreach but it kept on giving me the id of the last name in the for each.
2)Is there a way that i can click on add and and the data will be held and put in another html table below this html table but wont be inserted into database until i click on insert in the second table.
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div>Item</div></th>
<th><div>Quantity Left</div></th>
<th><div>Price</div></th>
<th><div>Quantity</div></th>
<th><div>Sell</div></th>
</tr>
</thead>
<tbody>
<?php
$count = 1;
$notarray = DataDB::getInstance()->get_rows_from_field('name');
foreach($notarray as $row):?>
<tr>
<td><?php echo $count++;?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['nickname'];?></td>
<td><?php echo $row['surname']; ?></td>
<form method="post" action="" role="form">
<td>
<div class="form-group">
<div class="">
<input type="number" class="form-control" name="kin" data-validate="required" data-message-required="Kin required" autofocus>
</div>
</div>
</td>
<td>
<div class="btn-group">
<button type="submit" class="btn btn-primary" name = "check">Add</button>
</div>
</td>
</form>
</tr>
<?php endforeach;?>
</tbody>
</table>
<br><br>
<div id="get_result">
</div>
<script type="text/javascript">
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'verify.php',
data: $('form').serialize() + '&ins=sellin' + '&id=<?php echo $row['name_id'];?>',
success: function(data)
{
jQuery('#get_result').html(data);
}
});
});
});
If I get you right, you mean you wanted to pick an item from list of items in table A and it should display in table B. Afterwards, you wanted to click submit button in table B to save the picked items from Table A?
Here is the solution:
Kindly name this file as test.php
<?php
/**
* Created by PhpStorm.
* User: SQ05
* Date: 06/01/2017
* Time: 06:31 PM
*/
//Note that data is a typical example of data u gotten from DB. so make sure u push all $row into an array
//such that u create something of this nature eg
// $data=array();
// $i=0;
//while($row=mysql_fetch_assoc($query)){
//$data[$i]=$row;
//$i++;
//}
// this will then create data of this nature below,
$data=array(
array('id'=>1,'name'=>'Loveth','age'=>23,'phone'=>'9889087455'),
array('id'=>2,'name'=>'Susan','age'=>51,'phone'=>'787987455'),
array('id'=>3,'name'=>'Precious','age'=>13,'phone'=>'98989087455'),
array('id'=>4,'name'=>'Hannah','age'=>21,'phone'=>'987087455'),
array('id'=>5,'name'=>'Kenneth','age'=>43,'phone'=>'569087455'),
);
?>
<div style="float:left;width:50%">
THE LIST OF ALL ITEMS
<table>
<tr>
<td>Name</td>
<td>Age</td>
<td>Phone</td>
<td>Action</td>
</tr>
<?php
$i=0;
for ($i=0;$i<count($data);$i++) {
$item=$data[$i];
?>
<tr>
<td><?php echo $item['name'];?></td>
<td><?php echo $item['age'];?></td>
<td><?php echo $item['phone'];?></td>
<td><button onclick='addToList(<?php echo json_encode($item);?>);'>Add</button></td>
</tr>
<?php
}
?>
</table>
</div>
<div style="float:left; width:50%">
THE ITEM TO BE SAVED
<div id="showToSave"></div>
</div>
<script src="bower_components/jquery/dist/jquery.js"></script> <!--Please install jquery base on ur own directory path-->
<script>
var listToSave=[]; // must be global
/**
* The add to list function that process data and add to list
* #param data
*/
var addToList= function(data){
var lenData=listToSave.length;
if(lenData>0){
//this is used to avoid duplicate
for(var j=0;j<lenData;j++){
if(data.id==listToSave[j].id) return;
}
}
listToSave.push(data);
console.log(listToSave);
document.getElementById('showToSave').innerHTML=createData(listToSave);
};
var createData= function (data) {
var len=data.length;
var tableToSave="<table><tr><td>Name</td> <td>Age</td> <td>Phone</td> <td>Action</td></tr>";
var i;
for(i=0;i<len;i++){
content=data[i];
tableToSave+="<tr><td>"+content.name+"</td><td>"+content.age+"</td><td>"+content.phone+"</td><td>" +
"<button onclick='deleteFromSave("+i+")'>Delete</button></td></tr>";
}
tableToSave+="</table><div><button onclick='saveData()' type='button'>Save</button></div>";
return tableToSave;
};
/**
* This is use to delete data added locally
*/
var deleteFromSave=function (index) {
listToSave.splice(index,1); //this is use to delete from list to save
document.getElementById('showToSave').innerHTML=createData(listToSave); //to rerender after delete
};
/**
* This is use to submit data
*/
var saveData=function () {
console.log('thjis=',listToSave);
$.ajax({
type: "POST",
url: "getData.php",
data: {list : JSON.stringify(listToSave)},
success: function(resp){
console.log('response=',resp);
}
});
};
</script>
Kindly name this as getData.php to process the submission of the list of added data using multiple value insertion approach.
<?php
/**
* Created by PhpStorm.
* User: SQ05
* Date: 06/01/2017
* Time: 07:28 PM
*/
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = json_decode(stripslashes($_POST['list'])); //the data here can now be used to create a multiple value insert to ur mysql db.
print_r(json_encode($data)); // this is used to send response back to ur page if using array buh echo if string
}
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);
}
I have this dropdown menu using form_helper in CodeIgniter:
<?php if($materialType): ?>
<?php
$material_options = array();
foreach($materialType as $rows){
$material_options[$rows->id] = $rows->category;
}
echo form_dropdown('materialType',$material_options,'','id="materialType"');
?>
<?php endif; ?>
<div id="materials"></div>
The code above is inside a <form> tag and I have this script:
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<script>
$(document).ready(function(){
$(document).on('change','#materialType',function(){
loadthis();
});
function loadthis(){
var ID = $('#materialType').val();
var dataString = 'id='+ ID ;
$.ajax({
type: "POST",
url: base_url + "index.php/admin/get_material",
data: dataString,
cache: false,
success: function(data)
{
$('#materials').html(data);
}
});
}
loadthis();
});
</script>
And here is the code that is being loaded:
<div id="materials">
<?php if($materials): ?>
<table>
<th>Name</th>
<th>Description</th>
<?php foreach($materials as $row): ?>
<tr>
<td><?php echo $row->mname; ?></td>
<td><?php echo $row->mdesc; ?></td>
<td>
<button class="try" value="<?php echo $row->id; ?>">Add</button>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<div class="alert alert-error" style="width:300px;">No Resource Available!</div>
<?php endif; ?>
$(document).on('click','.try',function(){
alert($(this).val());
return false;
});
And what i want is if the Add button is being click I can get the ID,mname and store it until the form is submitted.
How can I do that using .data() in jquery? or Any ideas on how to store it until the form is being submit.
I didn't thoroughly look at your code, but I noticed when you print your table rows in a loop you have the id="try" assigned to all of the rows. the html id-attribute is a unique identifier so the JS that is alerting the value will only return the value of the first id it will find (at least that's what i think). Try to use a class instread of an id and then use this in your js.
$(document).on('click','.try',function(){
alert($(this).val());
return false;
});
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 got stuck on the following issue. the issue is, I want to reload particular div of my page that also contain PHP script. My javaScript function is
function select_dayoff() {
jQuery('#loader').css('display','block');
var site = "<?php echo SITE_NAME.ROOT_FOLDER_NAME ?>"+"fschedules/dayoff";
jQuery.ajax({
type: "POST",
url: site,
data: "&fulldate="+MyDayoff.dayof,
success: function(msg){
jQuery('#loader').css('display','none');
}
});
}
and DIV is:
<span id="fill_available_time">
<?php $form->create(MEMBER_DAYOFF,array('id'=>'saveCancelDay','name'=>'saveCancelDay', 'type' => 'post', 'url'=>'/fschedules/dayoff')); ?>
<div class="profile">
<?php
if(!empty($dayoff_time)){
foreach($dayoff_time as $key => $val){
$res_dayoff_time[$val[MEMBER_DAYOFF]['dayoff']] = $val[MEMBER_DAYOFF]['dayoff'];
}
//echo $form->input('id_state',array('label'=>'','type'=>'select','id'=>'state_id', 'options'=>#$res_business_state, 'empty'=>'Please select...' ,'class'=>'required'));
//echo '<h2>Select date for cancel dayoff</h2>';
echo $form->input('dayoff_time', array('label'=>'','type'=>'select','id'=>'dayoff_time', 'options'=>$res_dayoff_time, 'empty'=>'Please select...' ,'class'=>'required' ,'onchange'=>'','style'=>'margin-left: 14px;'));
echo $form->submit('Cancel Dayoff', array('type'=>'submit','name'=>'saveCancelDay','id'=>'saveCancelDay'));
}else{
echo '<h2>No Dayoff is registered.</h2>';
}
?>
</div>
<?php $form->end(null); ?>
</span>
I want to refresh this DIV during above Ajax call.
Thanks in advance for any help.
create a html file xyz.html and add the html code
<?php $form->create(MEMBER_DAYOFF,array('id'=>'saveCancelDay','name'=>'saveCancelDay', 'type' => 'post', 'url'=>'/fschedules/dayoff')); ?>
<div class="profile"><?php
if(!empty($dayoff_time)){
foreach($dayoff_time as $key => $val){
$res_dayoff_time[$val[MEMBER_DAYOFF]['dayoff']] = $val[MEMBER_DAYOFF]['dayoff'];
}
//echo $form->input('id_state',array('label'=>'','type'=>'select','id'=>'state_id', 'options'=>#$res_business_state, 'empty'=>'Please select...' ,'class'=>'required'));
//echo '<h2>Select date for cancel dayoff</h2>';
echo $form->input('dayoff_time', array('label'=>'','type'=>'select','id'=>'dayoff_time', 'options'=>$res_dayoff_time, 'empty'=>'Please select...' ,'class'=>'required' ,'onchange'=>'','style'=>'margin-left: 14px;'));
echo $form->submit('Cancel Dayoff', array('type'=>'submit','name'=>'saveCancelDay','id'=>'saveCancelDay'));
}else{
echo '<h2>No Dayoff is registered.</h2>';
}
?></div>
<?php $form->end(null); ?>
function select_dayoff() {
jQuery('#loader').css('display', 'block');
var site = "<?php echo SITE_NAME.ROOT_FOLDER_NAME ?>"
+ "fschedules/dayoff";
jQuery.ajax( {
type :"POST",
url :site,
data :"&fulldate=" + MyDayoff.dayof,
success : function(msg) {
jQuery('#loader').css('display', 'none');
$('#fill_available_time').load('xyz.html')
}
});
}