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
}
});
});
Related
I am trying to make single page application with jquery using php i have created page which have 3 events inserts update and delete after each event data also be re fetched to display on table with new data but now the problem happening is when data be re fetched it not let events to work again like there are two button on every row of data edit and delete. but once you edit first row it not let you edit any other row. there must be way to make it but what could be solution i am newbie with jquery.
Here is my jquery.
$( document ).ready(function() {
// When click the button.
$("#save").on('click',function() {
// Assigning Variables to Form Fields
var category = $("#catname").val();
if(category){
$.ajax({
type: "post",
url: "insert.php",
asynch: false,
data: {
"category": category
},
success: function(data){
alert("Category Saved Successfully. ");
$("#ecname").html("");
$("#show").html(data);
$( '#form_category' ).each(function(){
this.reset();
});
}
});
}
else{
$("#ecname").html("fill category name");
}
});
});
Here is html of table.
<div class="m-portlet m-portlet--mobile">
<div class="row" id="categories">
<?php
$i = 1;
$categories = $obj->getallcategories();
echo '
<div class="col-lg-12">
<div class="m-portlet__body">
<table class="table table-striped- table-bordered table-hover table-checkable" id="m_table_1">
<thead>
<tr>
<th>
Id
</th>
<th>
category Name
</th>
<th>
category Name
</th>
<th>
Edit
</th>
<th>
Delete
</th>
</tr>
</thead>
<tbody id="show">
';
foreach($categories as $category){
echo'
<tr>
<td>'.$i.'</td><td>'.$category['cname'].'</td>
<td>categories</td>
<td><button value="'.$category['cid'].'" class="btn btn-primary get" id="get'.$category['cid'].'">edit </button></td>
<td><button class="btn btn-danger" id="del'.$category['cid'].'" value="'.$category['cid'].'" type="button">Delete</button></td>
</tr>
';
$i++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
Here is insert.php page which return data on ajax call of #save button click.
<?php
include("../functions/backend.php");
$obj = new Crud();
if(isset($_POST['category']))
{
$cname = $_POST['category'];
$obj->addcategory($cname);
$i = 1;
$categories = $obj->getallcategories();
foreach($categories as $category){
echo'
<tr>
<td>'.$i.'</td><td>'.$category['cname'].'</td>
<td>categories</td>
<td><button value="'.$category['cid'].'" class="btn btn-primary get" id="get'.$category['cid'].'">edit </button></td>
<td><button class="btn btn-danger" id="del'.$category['cid'].'" value="'.$category['cid'].'" type="button">Delete</button></td>
</tr>
';
$i++;
}
}
else {
echo "<script>alert('Something went wrong')</script>";
}
?>
edited with new self function which i want to make delegate.
function removeitem() {
var cid = $("[id^=del]").val();
$.ajax({
type: "post",
url: "delete.php",
asynch: false,
data: {
"cid": cid
},
success: function(data){
$("#show").html(data);
}
});
}
$("[id^=del]").confirm({
text: "Are you sure you want to delete ?",
confirm: function(button) {
//removeitem();
},
cancel: function(button) {
// nothing to do
},
confirmButton: "Yes I am",
cancelButton: "No",
post: true,
confirmButtonClass: "btn-danger",
cancelButtonClass: "btn-default",
dialogClass: "modal-dialog modal-lg" // Bootstrap classes for large modal
});
You need to read about event-delegation.
Delegated event handlers have the advantage that they can process
events from descendant elements that are added to the document at a
later time. By picking an element that is guaranteed to be present at
the time the delegated event handler is attached, you can use
delegated events to avoid the need to frequently attach and remove
event handlers.
For example, you need to do it like this:
$('body').on('click','#mybutton', function(){
//code here..
});
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 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
});
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.
i have the following table:
<table id="list_table" class="global" border="0" cellpadding="4" cellspacing="0">
<thead>
<tr>
<th>Grund</th><th>Von</th><th>Bis</th><th>Beschreibung</th><th></th></tr>
</thead>
<tbody>
<tr>
<td><select name="grund[1][1]">
<option value="krank">Krankheit</option>
<option value="urlaub" selected="selected">Urlaub</option>
<option value="sonstiges">Sonstiges</option>
</select></td><td><input name="von[1][1]" value="11.08.2011" onclick="displayDatePicker('von[1][1]')" type="text"></td><td><input name="bis[1][1]" value="16.09.2011" onclick="displayDatePicker('bis[1][1]')" type="text"></td><td><input name="beschreibung[1][1]" value="Blau machen" type="text"></td><td><img src="images/save.png"> <img src="images/delete.png"></td></tr>
</tbody>
</table>
And my JQuery is:
$('a[class*=saveChangedEntry]').click(function(event) {
event.preventDefault();
alert('That's it!');
});
So if I click on the link nothing happens ;(
And if i call the class in the more direct way ... even this does not work.
Any hints?
UPDATE:
Ok, something I didn't think about it and you could not know. The table is generated as a result of a couple of events, so I think I need to add the live() function to these links.
alert('That's it!');
is not properly escaped:
alert('That\'s it!');
Example
Make sure you wrap your code in a document.ready. Also the text you've placed inside the alert contains an unescaped quote:
$(function() {
$('a[class*="saveChangedEntry"]').click(function(evt) {
evt.preventDefault();
alert('That\'s it!');
});
});
Ok, perhaps I'm not getting the problem here too well, but I think that the issue is with the selector...
$(document).ready(function(){
$("a.saveChangedEntry").click(function(evt){
evt.preventDefault();
alert("foo!");
});
});
Hope I can help