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',
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 try to develop the " Load More " using Ajax & PHP & MVC Pattern
but i get a problem that the new row added can't get it with ajax (it can't know him)
My ajax code :
$(document).ready(function(){
$(document).on('click','#More',function(){
var id = $(".theID").last().val();
alert(id);
$.ajax({
url:'/more',
method: 'POST',
data:{id:id},
success:function(data){
//if(data != ''){
$('#rank').append(data);
/*}else{
$('#Load').remove();
}*/
}
});
});
});
My PHP code in controller
$datas = User::loadMore($_POST['id']);
echo View::getTemplate('User/data.html',['datas'=>$datas]);
My HTML code
<tbody id='rank'>
<tr>
<td>
1
</td>
<td>
<img alt='' src='img/test.jpg'/>
</td>
<button class='theID' value="{{rank.ID}}" style='display: none'></button>
</tr>
</tbody>
<button id='More' style=''>More</button>
data.html code
{% for key,data in datas %}
<tr>
<td>
{{key}}
</td>
<button class='theID' value="{{data.ID}}" style='display: none'></button>
</tr>
{% endfor %}
The ajax code work correctly but when I get the data the ID was always the first one.
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.
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 table in which data comes from the database.and I have the form on the same page which insert the data in the table.but when I insert data using $.ajax , it inserts record in database , but after reloading table in same function is not working, means it doesn't reload the table.
below is my code.
HTML
<div class="col-lg-8" id="value_table">
<div class="panel-body">
<div class="table-responsive">
<?php
$q=$db->query('select attr_val_id,attr_val,sortorder,status from db_attribute_value where attr_id="'.$attr_id.'"' );
?>
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Edit/Delete</th>
</tr>
</thead>
<tbody>
<?php $c=1; while($r=$q->fetch_assoc()){?>
<tr class=" gradeX">
<td><?php echo $c; ?></td>
<td><?php echo $r['attr_val']; ?></td>
<td><a href="add_attribute_val.php?id=<?php echo $r['attr_val_id']; ?>&attr_id=<?php echo #$r['attr_id']; ?>">
<button type="button" class="btn btn-default btn-circle"><i class="fa fa-pencil-square-o"></i></button>
</a>
<button type="button" class="btn btn-danger btn-default btn-circle" id="<?php echo $r['attr_val_id']; ?>" name="deleteRecord"><i class="fa fa-times"></i></button></td>
</tr>
<?php $c++;}?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
</div>
JQuery
$('#attr_val_form').submit(function(event) {
//$('.form-group').removeClass('has-error'); // remove the error class
//$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'attr_val' : $('input[name=attr_val]').val(),
'attr_id' : $('input[name=attr_id]').val(),
'sortorder' : $('input[name=sortorder]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'admin_operation.php?mode=add_attr_value', // the url where we want to POST
data : formData, // our data object
cache: false,
success: function(data)
{
if($.trim(data)== 'yes')
{
$("#value_table").html($("#value_table").html());
$("#notice")
.show()
.html('<div class="alert alert-success"<strong>Successfully !</strong> record added.</div>')
.fadeOut(3000);
}
else
{
$("#notice")
.show()
.html('<div class="alert alert-danger"<strong>Error !</strong>Record already exist.</div>')
.fadeOut(10000);
}
}
})
// using the done promise callback
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
I guess what you think this line should do is get the data from the response and substitute the same tag in your DOM:
$("#value_table").html($("#value_table").html());
You should use something like that instead:
$("#value_table").html($.parseHTML(data).find("#value_table").html());
This code has not been tested, but the main idea is to parse the data parameter and the find the #value_table element.
More info here: http://api.jquery.com/jquery.parsehtml/
As you say it seems like 'admin_operation.php?mode=add_attr_value' not success, try to call to always function instead success (for debugging it).
if the always function called successfully you have to return true from admin_operation.php
if not you have a problem on admin_operation.php after the insertion.