I'm new on Laravel and try to implement real live search and filter on my project, but it doesn't work at all. I dont understand ajax ver much and just copy paste the code from other website. I tried to understand the code and I think its correct but it doesn't work, so please help. Thanks
Here is my controller
public function search(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = Service::table('service')
->where('keterangan', 'like', '%'.$query.'%')
->orWhere('biaya', 'like', '%'.$query.'%')
->get();
}
else
{
$data = Service::table('service')
->orderBy('kodeService', 'asc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->kodeService.'</td>
<td>'.$row->keterangan.'</td>
<td>'.$row->biayaService.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output
);
echo json_encode($data);
}
}
This is the script
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('live_search.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('#table tbody').html(data.table_data);
}
});
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query)
});
});
Route :
Route::resource('service', 'ServiceController');
Route::get('service/search', 'Service#search')->name('live_search.action');
And index.blade
<table class="table table-striped table-hover table-bordered" id="table">
<thead>
<tr>
<th>Kode Service</th>
<th>Keterangan</th>
<th>Biaya</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
#foreach($service as $data)
<tr>
<td><?= $data->kodeService?></td>
<td><?= $data->keterangan ?></td>
<td><?= $data->biayaService?></td>
<td>
<a class="btn btn-sm btn-info" href="{{ route('service.edit', $data['kodeService']) }}"> <i class="oi oi-pencil"></i> Edit</a>
<button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#myModal"><span class="oi oi-trash"></span> Hapus</button>
</td>
</tr>
#endforeach
</tbody>
</table>
Put your route like this :
Route::get('service/search', 'ServiceController#search')->name('live_search.action');
Route::resource('service', 'ServiceController');
After that open the Browser Console panel (Press F12 to open it) and check the Ajax request in Network tab.
Where you can get the specific error if any in the Response tab.
If you need an extra route to your resource route,you should place the new route before the resource route.
Route::get('service/search', 'ServiceController#search')->name('live_search.action');
Route::resource('service', 'ServiceController');
currently I'm doing a bookstore system. almost similar with another shopping cart like amazon or whatsoever. my problem is how to apply multiple users to add product on cart . i do have login session and i have set MM_username for each user login. but when users add product into cart, it only appears name of one user.
here's the code below
if(isset($_POST["place_order"]))
{
$insert_order = "
INSERT INTO tbl_order(customer_id, creation_date, order_status)
VALUES(103, now(), 'pending')
";
$order_id = "";
if(mysqli_query($connect, $insert_order))
{
$order_id = mysqli_insert_id($connect);
}
$_SESSION["order_id"] = $order_id;
$order_details = "";
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
$order_details .= "
INSERT INTO tbl_order_details(order_id, product_name, product_price, product_quantity)
VALUES('".$order_id."', '".$values["product_name"]."', '".$values["product_price"]."', '".$values["product_quantity"]."');
";
}
if(mysqli_multi_query($connect, $order_details))
{
unset($_SESSION["shopping_cart"]);
echo '<script>alert("You have place an order...your order status will be inform through phone call within maximum 3 days..Thank you")</script>';
echo '<script>window.location.href="cart.php"</script>';
}
}
if(isset($_SESSION["order_id"]))
{
$customer_details = '';
$order_details = '';
$total = 0;
$query = '
SELECT * FROM tbl_order
INNER JOIN tbl_order_details
ON tbl_order_details.order_id = tbl_order.order_id
INNER JOIN tbl_customer
ON tbl_customer.CustomerID = tbl_order.customer_id
WHERE tbl_order.order_id = "'.$_SESSION["order_id"].'"
';
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$customer_details = '
<label>'.$row["CustomerName"].'</label>
<p>'.$row["Address"].'</p>
<p>'.$row["City"].', '.$row["PostalCode"].'</p>
<p>'.$row["Country"].'</p>
';
$order_details .= "
<tr>
<td>".$row["product_name"]."</td>
<td>".$row["product_quantity"]."</td>
<td>".$row["product_price"]."</td>
<td>".number_format($row["product_quantity"] * $row["product_price"], 2)."</td>
</tr>
";
$total = $total + ($row["product_quantity"] * $row["product_price"]);
}
echo '
<h3 align="center">Order Summary for Order No.'.$_SESSION["order_id"].'</h3>
<div class="table-responsive">
<table class="table">
<tr>
<td><label>Customer Details</label></td>
</tr>
<tr>
<td>'.$customer_details.'</td>
</tr>
<tr>
<td><label>Order Details</label></td>
</tr>
<tr>
<td>
<table class="table table-bordered">
<tr>
<th width="50%">Product Name</th>
<th width="15%">Quantity</th>
<th width="15%">Price</th>
<th width="20%">Total</th>
</tr>
'.$order_details.'
<tr>
<td colspan="3" align="right"><label>Total</label></td>
<td>'.number_format($total, 2).'</td>
</tr>
</table>
</td>
yes i know i shouldn't have put 103 as customer_id and i know that is the reason it will only read 103 user, but i have tried many ways include filter MM_username, ' ', $value and whatsoever. but it didn't work.
I am using CakePHP 2.3.6. In one of my projects, I have to implement the Searching feture, using AJAX. Normally, this is working, but I want that the page won't reload, the result table will be immediately updated with the data.
This is the Controller code:
public function searchData(){
$this->set(............);
$this->set(............);
$this->set(............);
if($this->request->is('post')){
$this->layout='ajax';
$this->autoRender=false;
if(!empty($data)){
$data=$this->request->data;
// Generating options
.
.
.
$result=$this->ModelName->find('all',$options);// "$options" is generated options
if(!empty($result)){
$this->set(compact($result));
$this->set('_serialize',array('result'));
print_r(json_encode($result));
$this->Session->setFlash("Searching Applicants Successful");
$this->set('result',$result);
}else
$this->Session->setFlash("No data found");
}else
$this->Session->setFlash("You didn't give any info to search for");
}
}
My View file(search_data.ctp) :
<h3>Search Result</h3>
<?php
echo $this->form->create();
echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
echo $this->Form->submit('Search');
echo $this->Form->end();
<div id="searchResult">
<?php if(!empty($result)){?>
<table class="table table-striped table-bordered table-hover">
<thead>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
<th>Field 4</th>
</thead>
<tbody>
<?php foreach($result as $applicant){?>
<tr>
<td><?php echo $result['ModelName']['field1'];?></td>
<td><?php echo $result['ModelName']['field2'];?></td>
<td><?php echo $result['ModelName']['field3'];?></td>
<td><?php echo $result['ModelName']['field4'];?></td>
</tr>
<?php }?>
</tbody>
</table>
<?php
}else
echo "No data found";
?>
</div>
Here, what I want is, when I submit the form, the "result" div will immediately appear, with the result data, organized in the table. I want to use Ajax here, so that users will get the result immediately, it'll improve the performance and user experience.
I've seen some youtube videos, where they load another page with the result, and shows that page in a div (it is called "success" div most of the time :) ), using Ajax. I can do it. But, I just want to do everything in 1 page, I don't want to use 2 pages to do it.
I tried this for ajax request and update my "result" div(in my search_data.ctp file) :
$this->Js->get('.search-form')->event('submit',$this->Js->request(array('controller'=>'cntrlr_name','action'=>'searchData'),array('async'=>true,'update'=>'#searchResult')));
And when I run the page, this is the output :
[{"Applicant":{"id":"3","name":"Name 2","email":"ssaha.316#gmail.com","mobile":"9082730572","contact_phone":"3465360980","office_phone":"2437845693","correspondence_address":"Correspondence Address 2","permanent_address":"Permanent Address 2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"},"ApplicantAcademicQualification":[{"id":"2","applicant_id":"3","level":"Bachelor(Pass)","degree_title":"B.A.","passing_year":"1999","institution":"Institution 2","result":"4.2","major":"Bengali Literature","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantEmploymentHistory":[{"id":"2","applicant_id":"3","employer":"Employer 2","position_held":"Position 2","industry":"Industry 2","department":"Department 2","major_responsibilities":"Responsibility 2","job_location":"Local","key_achievement":"Achievement 2","served_from":"1999-08-15","served_till":"2010-02-12","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantOther":[{"id":"2","applicant_id":"3","academic_activities":"Academic Activities 2","non_academic_activities":"Non Academic Activities 2","main_reason_for_applying":"Reason 2","worked_before":"0","last_position":"","work_location_constraint":"1","ready_to_join_on":"2008-08-14","expected_salary":"30k+","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantProfessionalQualification":[{"id":"2","applicant_id":"3","name_of_certificate":"Certificate 2","institute":"Institute 2","from":"2002-10-17","to":"2007-10-12","location":"Local Ins.","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantTraining":[{"id":"2","applicant_id":"3","title":"Title 2","institute":"Institute 2","training_year":"1995","location":"In Company","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}]},{"Applicant":{"id":"2","name":"Name 1","email":"user1#email.com","mobile":"715414918934","contact_phone":"2357295090","office_phone":"083656987398","correspondence_address":"Address 1_1","permanent_address":"Address 1_2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"},"ApplicantAcademicQualification":[{"id":"1","applicant_id":"2","level":"Secondary","degree_title":"S.S.C","passing_year":"2009","institution":"Institute 1","result":"4","major":"Science","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantEmploymentHistory":[{"id":"1","applicant_id":"2","employer":"Employer 1","position_held":"Position 1","industry":"Industry 1","department":"Department 1","major_responsibilities":"Responsibilities 1","job_location":"Local","key_achievement":"Achievements 1","served_from":"2005-03-12","served_till":"2007-11-26","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantOther":[{"id":"1","applicant_id":"2","academic_activities":"Academic Activities 1","non_academic_activities":"Non Academic Activities 1","main_reason_for_applying":"Reason 1","worked_before":"1","last_position":"Last Position 1","work_location_constraint":"1","ready_to_join_on":"2008-07-10","expected_salary":"20k-25k","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantProfessionalQualification":[{"id":"1","applicant_id":"2","name_of_certificate":"Certificate 1","institute":"Institute 1","from":"2011-10-11","to":"2012-09-11","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantTraining":[{"id":"1","applicant_id":"2","title":"Title 1","institute":"Institute 1","training_year":"2013","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}]}]
Is it possible ? How can I do it ? Please help me.
Thanks.
update your function searchData:
public function searchData(){
//just empty for showing the form only
}
add ajax function:
public function ajax_search(){
$this->layout="ajax";
$result = array();
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];
$field3 = $_POST["field3"];
$field4 = $_POST["field4"];
if( $field1 && $field2 && $field3 && $field4 ){ //change this depending on your queries
$data=$this->request->data;
// Generating options
.
.
.
$result=$this->ModelName->find('all',$options);// "$options" is generated option
}
$this->set("result", $result);
}
add view ajax_search.ctp:
<?php if($result):?>
<table class="table table-striped table-bordered table-hover">
<thead>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
<th>Field 4</th>
</thead>
<tbody>
<?php foreach($result as $applicant){?>
<tr>
<td><?php echo $result['ModelName']['field1'];?></td>
<td><?php echo $result['ModelName']['field2'];?></td>
<td><?php echo $result['ModelName']['field3'];?></td>
<td><?php echo $result['ModelName']['field4'];?></td>
</tr>
<?php }?>
</tbody>
</table>
<?php else:?>
No results.
<?php endif;?>
update you searchData.ctp:
<h3>Search Result</h3>
<?php
echo $this->Form->create("Search",array("default"=>false, "id"=>"SearchForm"));
echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
echo $this->Form->submit('Search');
echo $this->Form->end();
<div class="result">
;?>
<script type="text/javascript">
$(document).on('submit','#SearchForm',function(){
$.ajax({
type: "POST",
data:{
field1:$("#SearchField1").val, // the ids of your input or you can modify these if you have assigned ids to the input
field2:$("#SearchField2").val,
field3:$("#SearchField3").val,
field4:$("#SearchField4").val
},
beforeSend: function(){
$("#result").html("loading...");
}
url: "<?php echo $this->base;?>/{insert your controller name here}/ajax_search/",
success:function(data) {
$("#result").html(data);
}
});
});
</script>
Here are the steps:
Your search method returns data as JSON.
Then on your page loop data in jquery template.
Here is an example of how to use jQuery templates, and here it's documentation
Here is another approach
UPDATE
simple return json results from your search method:
public function searchData(){
$this -> layout = 'ajax';
$this -> autoRender = false;
if($this->request->is('post')){
if(!empty($data)){
$data=$this->request->data;
// Generating options
...
$result = $this->ModelName->find('all',$options);// "$options" is generated options
$this -> set(compact($result));
$this -> set('_serialize',array('result'));
echo json_encode($result);
}
}
}
Use and loop JSON results data
How can i get Hierarchical Data from db in Codeigniter. I read this :
http://www.sitepoint.com/hierarchical-data-database/
And i do good that but i cant optimize this tutorial with my model, controler and views
Default Category
|----- Sub category
| ----One more category
|----- Somthing else
I try but dont show sub category:
My model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$this->data[$row->id] = $row;
//echo str_repeat(' ',$level).$row['title']."\n";
}
return $this->data;
}
Controller :
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
Views:
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th> <?php echo str_repeat('|----', 0+1). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
And output is :
----Default
----Default
----Test Category 1
----Seccond Test Category 1
----Another Test Category 1
When i do this in model all work fine but when i try that to call in controler and loop in view i have result like above example:
This work onlu in model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
echo str_repeat('|-----',$level).$row->title."\n";
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
And like output i have :
Default
|----Test Category 1
|----Seccond Test Category 1
|----Another Test Category 1
Any one have solution or example thanks.
Try storing the level value for each category.
In your model:
public function fetchChildren($parent, $level){
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$row->level = $level;
$this->data[] = $row;
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
In your controller:
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
In your view
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th><?php echo str_repeat('|----', $row->level). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I have use two query to get result on the view.
To get the result of resultq1 i use foreach but how can i get result of resultq2 in view.
For each row of resultq1 i get record "reccount" in resultq2.
//controller
//Query 1
$q = $this->db->select(array(
'spf.id as id' ,
'spf.name',
"if(u.username != '',u.username,spf.added_by) as added_by ",
'spf.added_on'
))->from('sp_forum spf')->join('sp_users u', 'spf.added_by = u.id', 'left')->where($where)->order_by('spf.id desc')->limit(10, $page * 10)->get();
$resultq1= $q->result_array();
$data['resultq1'] = $resultq1;
$resultq2 = array();
$i=0;
foreach($resultq1 as $rec)
{
//query 2
$id = $rec['id'];
$q1 = $this->db->select("count('id') as reccount ")->from('sp_forum_topic spft')->where('spft.forumid',$id)->get();
$resultq2[$i] = $q1->row_object();
$i++;
}
$this->load->view('forumview', $data, true);
//view file
<table width="100%">
<tr>
<td class="th"> Details</td>
<td width="5%" class="th"> Answer</td>
<td width="15%" class="th">Started by</td>
<td width="15%" class="th">Created on</td>
</tr>
<?php foreach($resultq1 as $row):?>
<tr>
<td><?php echo $row['name'] ;?></td>
<td >---- </td> // here i want to use resultq2
<td><?php echo $row['added_by'] ;?></td>
<td ><?php echo $row['added_on'];?></td>
</tr>
<?php endforeach;?>
</table>
Array print in view for resultq2.
Resultq1 have 4 rows so that i get 4 value in resultq2.
Array ( [0] => stdClass Object ( [reccount] => 0 ) [1] => stdClass Object ( [reccount] => 0 ) [2] => stdClass Object ( [reccount] => 0 ) [3] => stdClass Object ( [reccount] => 2 ) ) 0002
You need to pass $resultq2 to the view as well.
In the controller, just before calling the view
$data['resultq2'] = $resultq2
You can now use $resultq2 in your view.
PS - SQL queries should be in models, not controllers.
Just Write '$data['resultq2'] = $resultq2' before loading the view,
$data['resultq2'] = $resultq2
$this->load->view('forumview', $data, true);
And you can retrieve it in the view by $result2 variable.
Just do var_dump($result2); in your view file, You will get the complete data of $result2 varaible.
And xbonez is right, do write your DB queries in the model, controller is only for login, and coordinating between (models, views, libraries, helper etc...)
I optimized your second query a bit, but logic is pretty much the same.
$q = $this->db->select(array(
'spf.id as id' ,
'spf.name',
"if(u.username != '',u.username,spf.added_by) as added_by ",
'spf.added_on'
))->from('sp_forum spf')->join('sp_users u', 'spf.added_by = u.id', 'left')->where($where)->order_by('spf.id desc')->limit(10, $page * 10)->get();
$resultq1= $q->result_array();
$data['resultq1'] = $resultq1;
$ids = array();
foreach($resultq1 as $result)
$ids[] = $result['id'];
$resultq2 = $this->db->select("count('id') as reccount ")->from('sp_forum_topic spft')->where_in('spft.forumid',$ids)->get();
foreach( $resultq2->result_array() as $res )
$newArr[$res['forumid']] = $res;
$data['resultq2'] = $newArr;
After resultq2 is indexed by original id, its easy to use id from resultq1 loop to show correct data
<table width="100%">
<tr>
<td class="th"> Details</td>
<td width="5%" class="th"> Answer</td>
<td width="15%" class="th">Started by</td>
<td width="15%" class="th">Created on</td>
</tr>
<?php foreach($resultq1 as $row):?>
<tr>
<td><?php echo $row['name'] ;?></td>
<td >
<?php
print_r( $resultq2[$row['id']]);
?>
</td> // here i want to use resultq2
<td><?php echo $row['added_by'] ;?></td>
<td ><?php echo $row['added_on'];?></td>
</tr>
<?php endforeach;?>
</table>
This should fix it.
Modify the controller - see comments also
<?php
//Query 1
$q = $this->db->select(array(
'spf.id as id',
'spf.name',
"if(u.username != '',u.username,spf.added_by) as added_by ",
'spf.added_on'
))->from('sp_forum spf')->join('sp_users u', 'spf.added_by = u.id', 'left')->where($where)->order_by('spf.id desc')->limit(10, $page * 10)->get();
$resultq1 = $q->result_array();
$data['resultq1'] = $resultq1;
$resultq2 = array();
foreach ($resultq1 as $rec) {
//query 2
//echo $id = $rec['id']; //Test and See if all IDs echo out correctly
$data["id"] = $id; //Add this for the ID
$q1 = $this->db->select("count('id') as reccount, spft.forumid")->from('sp_forum_topic spft')->where('spft.forumid', $id)->get();
$resultq2[$id] = $q1->result(); //Change this line
$data["resultq2"][$id] = $resultq2[$id]; //Add this line
}
//echo "<pre>";
//$export = var_export($data, true);// Test the returned value...
//echo "</pre>";
$this->load->view('forumview', $data, true);
?>
In Your view
<table width="100%">
<tr>
<td class="th"> Details</td>
<td width="5%" class="th"> Answer</td>
<td width="15%" class="th">Started by</td>
<td width="15%" class="th">Created on</td>
</tr>
<?php //foreach ($resultq1 as $row): ?>
<?php foreach ($data as $row): ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td>
<?php
//$resultq2 is now array
//print_r($resultq2); //Do this so you can see the depth of the array
foreach ($resultq2 as $counts) {
foreach ($counts as $count) { //The second foreach might be necessary - please test
echo $count->reccount; //This should print out the count result
//echo "<br />";
}
}
?>
</td>
<td><?php echo $row['added_by']; ?></td>
<td ><?php echo $row['added_on']; ?></td>
<td >
</td>
</tr>
<?php
endforeach;
exit;
?>
</table>
I haven't had time to test it but it should work. Let me know if you find any issues: