Display Search result in a table - php

So i create a search engine in my laravel application, the only problem i have is displaying it on the same page,
this is what i have in my views
<div class="search">
{{Form::open(array('url' => 'admin/search', 'method' => 'post'))}}
{{Form::text('keyword',null,array(
'class' => 'form-control',
'placeholder' => 'Enter keyword...'
))}}<br>
{{Form::submit()}}
</div>
<br>
<div class="searchs">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<th>Title</th>
<th>Date Created</th>
<th>Actions</th>
</thead>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</div>
and in my controller
public function search_keyword()
{
$input = Input::get('keyword');
$result = Post::where('title','LIKE','%' .$input. '%')->get();
return Redirect::route('index')
->with('result',$result);
}
but i was hoping that i could do this in ajax request but I don't know jquery or even js.. help

You have to catch the submit of the form with Javascript (vanilla or e.g. jquery), find the value the user is searching for and start an ajax request. (jQuery $.get() or native XMLHttpRequest())
Now you need to make sure that laravel accepts the ajax request properly and return the request as JSON.
If your request successfully returns data, use the success function of the ajax request to process the data. During the search, you could show some loading icon to notify the user that the search process is running.
To start with, add an id to the form and use jquery to listen for the submit event.
<script type="text/javascript">
$('#my-form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "/api/search",
type: 'POST',
data: {
value: $("input:first").val()
},
dataType: 'json',
success: function (response) {
console.log(response);
}
});
});
</script>
Next, register a route for the /api/search request and return your search request with return response()->json(['result' => $result]); (laravel 5)
If everything is right, you should see the result in the console of your browser.

Related

Table dosent load data using ng-repeat

Im loading data from php to a variable in angular js but the table dosent load the data and remains empty
<script>
var app = angular.module('clientesApp', []);
app.controller('clientesController', function ($scope,$interval) {
$scope.clientes =[];
$scope.error = [];
$scope.alertMsg=false;
$scope.carregarClientes = function () {
$.getJSON(
"/abcaia/getclientes.php", {},
function (jsonData) {
$scope.clientes = jsonData;
console.log($scope.clientes);
$scope.applay;
});
};
});
</script>
I added a button that calls the function of requesting data and the data loads after that, but i whant for it to load when the page loads
<div ng-init="carregarClientes()">
<button id="btnEnviaComent" class="btn btn-success btn-x" ng-click="carregarClientes()">
Enviar
</button>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>id</th>
<th>info</th>
</tr>
</thead>
<tbody ng-repeat = "c in clientes" >
<td>{{c.idCliente}}</td>
<td>{{c.info}}</td>
</tbody>
</table>
</div>
Just invoke $scope.carregarClientes() after the function declaration. You will get the same results as clicking the button.
Found the problem
i had $scope.apply; insted of $scope.$apply();

Can't show the user's detail data in html (but can show the array with print_r()) "codeigniter"

I want to show the user detail modal when I click the detail button next to every that users name, but the problem is I can't display the "user_detail" data that I got from controller, it make me so confusing because when I display from controller using print_r() it show perfectly the data array that I want. Now I just want to display it as html like I display all user in the first place.
Here is my full code, I think we should just focus on the get_detail() method in the controller.
model/test_model.php:
function get_user()
{
$query = $this->db->query("SELECT * FROM tb_users ");
$result = $query->result_array();
return $result;
}
function get_detail($user_id)
{
$query = $this->db->query("SELECT * FROM tb_users where user_id = '".$user_id."'");
$result = $query->result_array();
return $result;
}
Controller/Welcome.php:
public function index()
{
$data["datakcp"] = $this->test_model->get_user();
$this->load->view('welcome_message',$data); // do this by loading a "view" that formats the data we gather here
}
public function get_user($user_id = null)
{
// get the user_id from the ajax request
// this means if $user_id is set (not null) then make $user_id = $user_id. Otherwise, make $user_id = posted input
$user_id = ($user_id) ? $retailer_id : $this->input->post('user_id');
$datadetail= $this->test_model->get_detail($user_id);
echo json_encode($datadetail);
}
Views/my_view.php:
<div class="container" style="width:700px;">
<h3 align="center"> </h3>
<br>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="70%">Employee Name</th>
<th width="30%">View</th>
</tr>
<?php foreach($datakcp as $user){ ?>
<tr>
<td><?php echo $user["user_name"] ?></td>
<td><input type="button" name="detail" value="detail" id="<?php echo $user["user_id"] ?>" class="btn btn-info btn-xs view_dawta"></td>
</tr>
<?php } ?>
</table>
</div>
</div>
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" id="employee_detail">
<table>
<thead>
<th>Username<th>
<th>Campaign</th>
</thead>
<tbody id="userDetail">
</tbody>
</table>
</div>
</div>
</div>
My jQuery ajax script:
<script>
$(document).ready(function(){
$('.view_dawta').click(function(){
var user_id= $(this).attr("id");
$.ajax({
url:"index.php/Welcome/get_user",
method:"post",
data:{user_id:user_id},
success:function(data){
console.log(data)
$.each((JSON.parse(data)), function(key, value){
$('#userDetail').append(
'<tr>'+
'<td>'+value.user_name+'</td>'+
'<td>'+value.campaign_name+'</td>'+
'</tr>'
);
});
$('#dataModal').modal("show");
}
});
});
});
</script>
get_user function is not returning anything. (Note: when you try your print_r or var_dump statement, the output of print_r or var_dump statement is returned, and otherwise nothing is being returned).
Put echo json_encode($datadetail); at the end in get_user function and receive json data in response. You will then have to use and format that json data in your ajax success function.
Alternatively, you can return formatted html from get_user function, in which case your $('#employee_detail').html(data); should work as it is.
EDIT:
1- Here is a basic ajax call you should use to receive json data:
$.ajax({
url:"index.php/Welcome/get_user",
method:"post",
contentType: "application/json;",
dataType: "json",
data:{user_id:user_id},
success:function(data){
$('#employee_detail').html(data);
$('#dataModal').modal("show");
}
});
2- And in your get_user function, put echo json_encode($datadetail); at the end. At this point, you should be able to see json data in your modal.
3- In get_user function, replace $datadetail["userdetail"] with $datadetail. And at the end of the function, echo json_encode($datadetail);.
4- In my_view.php, construct a table inside <div class="modal-body" id="employee_detail"> like below (this is just one way, you can decide a different approach if you wish):
<table>
<thead>
<th>Username</th>
<th>Campaign</th>
<!-- include more <th> tags for other user data -->
</thead>
<tbody id="userDetail">
</tbody>
</table>
5- In ajax call, your success function can be:
success:function(data){
$.each(data, function(key, value){
$('#userDetail').append(
'<tr>'+
'<td>'+value.user_name+'</td>'+
'<td>'+value.campaign_name+'</td>'+
/* include more <td> tags for other user data */
'</tr>'
);
});
$('#dataModal').modal("show");
}
6- This should be enough to give you a complete idea of how to receive and handle json data and also format it into html. This should be able to get you started. You can work on other formatting details etc. now.
On a related note, you have duplicate user_id in your returned data. Do check that.
Hope this helps.

Dropdown content not showing when loading dynamic generated buttons

I have a question regarding MaterializeCSS.
I have an html table that has an option button that will display dynamic options generated based on the user.
This all works fine on the first run (when loading the page), yet when I reload the table contents (including the buttons) using AJAX the dropdown content won't show up anymore. Whilst the button click event still gets triggered.
I have tried multiple solutions yet none of these worked for my case.
Table (tbody content generated by foreach loop in php):
<table class="table highlight">
<thead>
<tr>
<th class="center-align">
<input type="checkbox" id="checkAllUsers" class="checkToggle checkAllUsers"
data-target="#boxUsers table tbody [type=checkbox]">
<label for="checkAllUsers"></label>
</th>
<th>Username</th>
<th class="hide-on-small-only">Email</th>
<th style="text-align:center;" class="hide-on-small-only">Allowed</th>
<th style="text-align:center;">Employee</th>
<th>Action</th>
</tr>
</thead>
<tbody class="usertablebody">
<tr>
<td class="center-align">
<input type="checkbox" class="selectedUsers" name="u-1" id="u-1">
<label for="u-1"></label>
</td>
<td>jGeluk</td>
<td class="hide-on-small-only">jonah#example.com</td>
<td style="text-align:center;">Yes</td>
<td style="text-align:center;">No</td>
<!-- ACTION BUTTON HERE -->
<td>
<div class="actions">
<a class="dropdown-button showuseroptions btn-flat waves-effect" uid="1" href="#"
data-activates="showUserOptions">
<i class="large material-icons">more_vert</i>
</a>
</div>
</td>
</tr>
</tbody>
Dropdown content:
<ul id="showUserOptions" class="dropdown-content main-dropdown lighten-2">
<li>Loading...</li>
</ul>
Loading dynamic dropdown content (this runs without any problems on page load):
$("body").on('click', ".showuseroptions", function(event) {
var uid = $(this).attr('uid');
var btn = this;;
toggleLoader();
jQuery.ajax({
type: "POST",
url: base_url + "ajax_admin_controller/fetch_user_options",
dataType: 'text',
data: {uid:uid},
success: function(res) {
if (res)
{
//"ul#showUserOptions"
$("ul#showUserOptions").html(res);
}
toggleLoader();
}
});
});
Refresh table function:
function refreshUserTable()
{
toggleLoader();
jQuery.ajax({
type: "POST",
url: base_url + "ajax_admin_controller/fetch_users_table",
dataType: 'text',
success: function(res) {
if (res)
{
$(".usertablebody").html(res);
toggleLoader();
}
}
});
}
Using
$(this).dropdown();
as stated in the documentation doesn't have any effect.
I hope somebody can help me out.
Thanks,
Jonah
call the dropdown after the ajax is completed and the html is appended
toggleLoader();
$('.showuseroptions').dropdown();
make sure you have a unique id for each dropdown
change
dataType: 'html',

I am unable click on datatables row to send data to text field in Laravel 5.4

I have a web app in Laravel 5.4. In some modules, I have a main form from which datatables are called in a modal dialog window (for example: if I click on a search button, the modal window appears with the datatables in it).
What I am trying to achieve is that when I click on the data in the datatables it closes the modal window and get the clicked info and display it in a specified field in a form, the main form.
But after I put all the necessary scripts, nothing happens when I click on the data in the datatable.
a. HTML Table
<section class="panel">
<div class="table-responsive">
<table width="100%" id="pere-table" class="table" >
<thead>
<tr>
<th>NNID</th>
<th>Nom</th>
<th>Post-Nom</th>
<th>Prenom</th>
</tr>
</thead>
<tbody>
<tr >
<td class="NNID"></td>
<td class="nom"></td>
<td class="postnom"></td>
<td class="prenom"></td>
</tr>
</tbody>
</table>
</div>
</section>
<small><span class="glyphicon glyphicon-plus"></span> Ajouter</small>
b.Input Field to receive Data has pere_nouv as its id
Controller fetching the data
public function recherchePere ()
{
$pere = Pere::join('t_individus','t_adultes.nnid', '=',
't_individus.nnid')
->select(['t_individus.nom', 't_individus.postnom',
't_individus.prenom', 't_individus.nnid'])
->where('t_individus.sexe','=','0');
return Datatables::eloquent($pere)->make(true);
}
the ajax for the datatable
#push('scripts')
<script type="text/javascript">
$(function() {
$('#pere-table').DataTable({
processing: false,
serverSide: true,
ordering: false,
ajax:'http://127.0.0.1:8000/nouveau_ne/data_peres',
columns :[
{data : 'nnid', name:'t_individus.nnid'},
{data : 'nom', name:'t_individus.nom'},
{data : 'postnom', name:'t_individus.postnom'},
{data : 'prenom', name:'t_individus.prenom'},
]
});
});
</script>
#endpush
The route
Route::get('/nouveau_ne/data_peres', ['as' => 'nouveau_ne','uses' =>
'AdulteController#recherchePere']);
Route::get('/nouveau_ne/pere', [ 'uses' => 'AdulteController#index']);
The Jquery Script for Clicking on a row to feed a text box
<script type="text/javascript">
var vpWidth = $(window).width();
var vpHeight = $(window).height();
var textClickedOn;
var pereNouv = $("#pere_nouv");
var nnid = $(".NNID");
nnid.click(function(){
//Get text clicked on
textClickedOn = $(this).text();
//alert(textClickedOn);
pereNouv.val(textClickedOn);
});
</script>
QUESTION: What am I doing wrong? Your help and tips will be highly appreciated
Click event is attachted to existing elements on page load. The key word here is existing. When we load something with ajax we manipulate DOM. We are placing totally new element.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time
try something like :
$('body').on('click', '#pere_nouv', function (event) {
// your code goes here
});
or this :
$(document).on('click','body #pere_nouv',function(){
// additional code
});

Tablesorter and saving sort

I have a table with some information.
At first time it is generate from php-script and then every n-seconds check database.
Then I've installed tablesorter plugin. It's okay, but now, after getting information from database(if table was sorted by several fields) sort "configuration" resets.
So I've found some information about saveSort plugins, download jquery.tablesorter.widgets.js include it into my project. In plugin's documentation I've found some instruction like how to.
$("table").tablesorter({
widgets: ["saveSort"]
});
But it doesn't fix my problem. After getting results the saved sort resets.
So, here is the code of my script:
$(document).ready(function(){
$("table").tablesorter({
widgets: ["saveSort"]
});
function get_op(){
var dataSend = "to teh mooon";
jQuery.ajax({
type: "POST",
url: "get_url",
dataType:"html",
data:dataSend,
success:function(response){
$("#recent_op tbody").html(response);
$("#recent_op").trigger("update");
},
error:function (xhr, ajaxOptions, thrownError){
$("#recent_operations").html(thrownError);
}
});
}
setInterval(function(){get_op()}, 10000);
});
Here is simple table that I used.
<table class="table table-bordered table-hover table-striped tablesorter" id = "recent_op">
<thead>
<tr>
<th>header # <i class="fa fa-sort"></i></th>
....
</tr>
</thead>
<tbody>
<tr>
<td>Body</td>
....
</tr>
....
<tr>
<td>Body</td>
....
</tr>
</tbody>
</table>
So, no errors, everythings from tutorial, but it doesn't work good. I think I'm use this widget in a wrong way.
The saveSort widget requires:
jQuery v1.4.1+
$.tablesorter.storage utility which is also included in the jquery.tablesorter.widgets.js. I mention this in case the file was modified some how.
A browser that supports localStorage, or cookies (fallback method if localStorage is not supported).
The save sort can be enabled/disabled using the widget option
$(function(){
$("table").tablesorter({
widgets: ["saveSort"],
widgetOptions : {
// if false, the sort will not be saved for next page reload
saveSort : false
}
});
});

Categories