What I want to achieve is to delete an entire row. First I display the table, then if you click on "delete" button from every row then a confirmation modal shows up asking you if you want to delete that row.
I'm trying to work with jquery, ajax, json and PHP. I'm still learning of course.
So far what I have is this:
Javascript file:
function callToModal(data){
$('#myModal3 .modal-body p').html("Desea eliminar al usuario " + '<b>' + data + '</b>' + ' ?');
$('#myModal3').modal('show');
$('.confirm-delete').on('click', function(e) {
e.preventDefault();
var id = $(this).data('id');
$('#myModal3').data('id', id).modal('show');
});
$('#btnYes').click(function() {
// handle deletion here
var id = $('#myModal3').data('id');
alert(id);
$.ajax({
url: "deleteFrontUser",
type: 'POST',
data: {
id:id
},
success: function(html){
//alert(html);
$('[data-id='+id+']').parents('tr').remove();
$('#myModal3').modal('hide');
}
});
return false;
});
};
In my admin.php file:
public function deleteFrontUser(){
// var_dump($_POST['id']);die();
$rowId = $_POST['rowId'];
$result = array();
$front = UserDs::getInstance()->getUserById($id);
UserDs::getInstance()->deleteItem($front);
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}
The view (please notice that I'm using Smarty template engine):
<div class="portlet-body">
<table class="table table-striped table-hover table-users">
<thead>
<tr>
<th>Avatar</th>
<th class="hidden-phone">Usuario</th>
<th>Nombre</th>
<th>Apellido</th>
<th class="hidden-phone">Email</th>
<th class="hidden-phone">Provincia</th>
<th class="hidden-phone">Miembro desde</th>
<th>Estado</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{foreach $frontusers as $frontuser}
<tr>
{if $frontuser->frontavatar_id eq null}
<td><img src="{site_url()}assets/img/avatar.png" alt="" /></td>
{else}
<td><img src="{site_url()}assets/img/avatar1.jpg" alt="" /></td>
{/if}
<td class="hidden-phone">{$frontuser->username}</td>
<td>{$frontuser->name}</td>
<td>{$frontuser->lastname}</td>
<td class="hidden-phone">{$frontuser->email}</td>
<td class="hidden-phone">{$frontuser->state}</td>
<td class="hidden-phone">{$frontuser->creation_date|date_format:"%Y/%m/%d"}</td>
{if $frontuser->status eq 2}
<td ><span class="label label-success">Activo</span></td>
{else}
<td ><span class="label label-warning">No Activo</span></td>
{/if}
<td><a class="btn mini blue-stripe" href="{site_url()}admin/editFront/{$frontuser->id}">Modificar</a></td>
<td>Eliminar</td>
</tr>
<!-- modal -->
<div id="myModal3" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel3" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel3">Eliminar</h3>
</div>
<div class="modal-body">
<p></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cerrar</button>
<button data-dismiss="modal" class="btn red" id="btnYes">Confirmar</button>
</div>
</div>
<!-- end modal -->
{foreachelse}
<tr>
<td colspan="2"><span class="text-error"><i class="icon-exclamation"></i> No hay Usuarios cargados.</span></td>
</tr>
{/foreach}
</tbody>
</table>
</div>
The modal displays when you click on delete button of an specific row, but here's the funny thing: the first time you press delete, it doesn't erase the row. When you press that or any other row (after pressing once delete) the row is deleted. So that is one problem, and the other problem is that I can't manage to send data to my php file so I can erase it from the database.
How can i solve this?
I have a customized fiddle with this, if you want to check out: code
url has to be a valid site located within your website, you can't have a function name within url, since the AJAX call won't know in which file the function is located.
So your url must be:
url: "admin.php"
You can, however, add another parameter into your AJAXcall to tell admin.php which function it should execute, something like this would work:
$.ajax({
url: "admin.php",
type: 'POST',
data: {
id:id,
func:"deleteFrontUser"
},
success: function(html)
{
//alert(html);
$('[data-id='+id+']').parents('tr').remove();
$('#myModal3').modal('hide');
}
});
So on admin.php you must receive the posted data BEFORE you enter the function, and you can parse the func variable to tell which function to execute:
$rowId = $_POST['id'];
$func = $_POST['func'];
switch ($func)
{
case 'deleteFrontUser':
deleteFrontUser($rowId);
break;
default:
// function not found.
break;
}
Wherea deleteFrontUser looks something like this:
public function deleteFrontUser($rowId)
{
$result = array();
// Rest of the code.
echo json_encode($result);
}
Maybe you need to modify this a bit but this should give you the idea.
For more information take a look at the $.ajax documentation.
Note:
For best practice's cause, use php's isset function to determine whether the data was actually posted or not. The ternary operator makes this very easy and short:
$emptyString = "";
$rowId = isset($_POST['id']) ? $_POST['id'] : $emptyString;
$func = isset($_POST['func']) ? $_POST['func'] : $emptyString;
I also recommend using jQuery's .on function, and let it take the parameter "click" and the function of which will be triggered on the click event. .click is in general bad practice because it's unable to detect changes within the DOM tree so when you update it with new HTML you're screwed, .on allows you to add new elements to the dom tree but still being able to listen to events corresponding to them.
Solution is this:
See my previous post in order to have the correct js file and view: post
Php code for deleting entire row from the database would be:
public function deleteFrontUser(){
$rowId = $_POST['id'];
$result = array();
$front = UserDs::getInstance()->getUserById($rowId);
UserDs::getInstance()->deleteItem($front);
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}
Related
Sorry to bother, I'm having a trouble passing and ID to my AJAX function.
I wanted to pass the ID of the selected table row to my AJAX function and use it for my query in my controller
this is the code for my table row
<div class="container">
<h2 style="margin-top: 12px;" class="alert alert-success">Details</h2><br>
<div class="row">
<div class="col-12">
<table class="table table-bordered" id="">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<td colspan="2">Action</td>
</tr>
</thead>
<tbody id="users-crud">
#foreach($merchants as $merchant)
<tr id="user_id_{{ $merchant->id }}">
<td>{{ $merchant->id}}</td>
<td>{{ $merchant->first_name }}</td>
<td>{{ $merchant->email }}</td>
<td><a id="getData" onClick="getData({{$merchant->id}})" class="btn btn-info">Show</a>
</td>
</tr>
#endforeach
</tbody>
</table>
{{ $merchants->links() }}
</div>
</div>
</div>
upon click show ID should pass it to my AJAX function,
this is the code of the script
<script type=text/javascript>
$(document).ready(function() {
});
function getData(id){
$('#myModal').modal('show');
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "getproducts/",
// dataType: 'json',
data: {id: id}, // This will be {id: "1234"}
success: function (data) {
$("#id").html(data.id);
$("#first_name").text(data.first_name);
}
});
};
</script>
And ID will be use for my query in my controller, this is my controller's code, note that the number 1 in my where query is hard coded, I wanted to put the ID that I get from the selected table
public function getproducts()
{
$merchants = DB::table('merchants')
->select('merchants.*', 'product.product_name as product_names')
->join('product','product.id','=','merchants.id')
// THE NUMBER 1 IS HARD CODED
->where('merchants.id', 1)
->paginate(8);
return response()->json($test, 200);
}
Every method in a Laravel Controller can have arguments "injected" into them, including the Request $request variable. Add this to the top of your Controller after your namespace declaration:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
Then modify your method:
public function getproducts(Request $request) {
...
}
Then, instead of hard-coding the value 1, you pull it from your $request object:
->where('merchants.id', $request->input('id'))
The full documentation can be seen here:
https://laravel.com/docs/9.x/requests#accessing-the-request
Your code seems fine to me. What is the issue you are facing? But you can improve code by bit more.
<td><a id="getData" onClick="getData({{$merchant->id}})" class="btn btn-info">Show</a>
Instead you can use a global class. Also using same HTML id in a class is not good practice.
<td><a class="merchant_info" data-id="{{$merchant->id}}" class="btn btn-info">Show</a>
Now need modification to jQuery code
<script type=text/javascript>
$(document).ready(function() {
$('.merchant_info').click(function(e){
e.preventDefault();
var dataId = $(this).attr("data-id");
// Now do the Ajax Call etc
});
});
</script>
I have HTML table with dynamically generated contents. A td in the table contains a form. What I want is to remove the table from the page once this form is submitted because another page will be included at form submitting. I am using ajax and php. How can I amend my code below to remove the table once the form is submitted?
JAVASCRIPT
function chk(item_id){
$.ajax({
type:"post",
url:"edit_form.php",
data: {
id: item_id,
name: $('#name-'+item_id).val()
},
cache:false,
success: function(html){
$('#msg').html(html);
}
});
$('#forms').click(function(){
$('#table').hide();
});
return false;
}
HTML
<div id="msg"></div>
<div id="table">
<table align="center">
<tbody>
<tr>
<th>S/N</th>
<th>Subject</th>
<th>Edit</th>
</tr>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $subject;?></td>
<td>
<form id="myform">
<input type="text" id="name-<?php echo $item_id;?>" hidden name="name" value="<?php echo $item_id;?>" >
<button type="submit" id="forms" onclick="return chk(<?php echo $item_id;?>)">Edit</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
$('#forms').click(function(){
$('#table').hide();
});
At the moment, when the form submits, the above code means you're creating an event handler to listen for the next time the button is clicked, which would then hide the table at that time.
To hide it as soon as the form is submitted, then simply remove the event handler part and just write
$('#table').hide();
by itself within the "chk" function.
N.B. If you don't want it to hide until after the ajax call is completed successfully, then move it inside the "success" function.
According to your question title:
You can simply add these lines in your ajax success: :
$("#table table").remove();
OR
You can set innerHTML of div to empty
$("#table").html("");
I hope this should work.
why do you need a <form> tag anyway? a more simple approach which doesn't involve jQuery
HTML
<input name="" />
<button id="submit">Submit</button>
JS
submit.onclick = function(){
element = document.querySelector('holderClass');
element.style.display = 'none'; // or any element
// ...ajax here
}
you might need document.querySelector()
//In success block you can remove the table by using $('#table').html("");
function chk(item_id){
$.ajax({
type:"post",
url:"edit_form.php",
data: {
id: item_id,
name: $('#name-'+item_id).val()
},
cache:false,
success: function(html){
$('#msg').html(html);
$('#table').html("");
}
});
return false;
}
I'm populating a table from my database and it looks like this :
<form name = "Form" role="form" action ="php/teilnehmen.php" method="POST">
<fieldset>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Studienfach</th>
<th>Teilnehmer/in</th>
<th>Teilnehmen</th>
</tr>
</thead>
<tbody>
//<?php php code.....
$i =0;
$sizeofstudienfaecherseperate =
count($studienfaecherseperate);
for ($i; $i < $sizeofstudienfaecherseperate; $i++) {
?>
<tr class="odd gradeX">
<td ><?php echo($i+1);?></td>
<td class="studienfach"><?php echo($studienfaecherseperate[$i]);?>
<input type="hidden" name="PARAM_STUDIENFACH" id="PARAM_STUDIENFACH"
value="<?php echo($studienfaecherseperate[$i]);?>"> </input>
</td>
<td ><?php echo($teilnehmer[$i]);?></td>
<td width="10%">
<?php if ($teilnahmestatus[$i] =="0"){ ?>
<button type="submit" class="btn btn-success use-address"
name="teilnehmern"id="teilnehmen">Teilnehmen</button>
<?php }else{?>
<button type="submit" class="btn btn-danger use-address" name="teilnahme-beenden"
id="teilnahme-beenden">Teilnahme beenden</button>
<?php }?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset> <!-- /.table-responsive -->
the table is shown great, and my problem is when i try to submit my second column value "PARAM_STUDIENFACH" of a specific row to my php webservice. It always gives me back the last value. I know that because I'm using the same id in every row so it will be overwritten. I tried using JavaScript to return the value of the clicked row from other questions in the forum but it didn't work for me. I'm using a bootstrap table if that helps.
EDIT 1 :
Thanks to #Taplar answer I managed to find a solution to my problem. I used this JavaScript to retrieve the data and ajax to send a post request. This is the code I used :
$(".use-address").click(function() {
var item = $(this).closest("tr") // Finds the closest row <tr>
.find(".studienfach") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$.ajax({
type: "POST",
dataType: "json",
url: "php/teilnehmen.php",
data: {PARAM_STUDIENFACH:item},
success: function(data){
alert(item);
},
error: function(e){
console.log(e.message);
}
});
});
my problem now is in the alert the "item" shows correctly but in my database it is saved as the following example :
item = a (shows in alert a)
item = a \n (it's saved like that in the database with spaces afeter \n)
i tried to trim the item before sending it but i got the same result
to get the item sent by ajax i'm using this line of code in :
$studienfach = null;
if(isset($_POST['PARAM_STUDIENFACH']))
$studienfach = $mysqli->real_escape_string($_POST['PARAM_STUDIENFACH']);
EDIT 2:
i managed to solve my second problem by doing this :
$pos= strpos($studienfach, "\\");
$studienfachtemp = substr($studienfach, 0,$pos);
trim($studienfachtemp);
if there is more elegent or correct way to do it ! please post it ! thank you all.
<elem1>
<elem2 class="getMe"></elem2>
<elem3></elem3>
</elem1>
Quick contextual lookup reference. Say you have a click event bound on all 'elem3' on your page. When you click it you want to get the associated 'elem2', not all of them. With the class you can contextually look this element up by doing...
//'this' being the elem3 that was clicked
$(this).closest('elem1').find('.getMe');
From the element you clicked, it will find the shared 'elem1' parent of both 'elem2' and 'elem3' and then find only the '.getMe' that belongs to that parent.
More reading material: http://learn.jquery.com/using-jquery-core/working-with-selections/
I am using editable plugin to preform in place edit
This is the code I am using that I got from their Doc page, it is supposed to be used for adding new records, But I want to use it to modify records)
<script>
$(document).ready(function() {
//init editables
$('.myeditable').editable({
url: '/post',
placement: 'right'
});
//make username required
$('#new_username').editable();
//automatically show next editable
$('.myeditable').on('save.newuser', function(){
var that = this;
setTimeout(function() {
$(that).closest('td').next().find('.myeditable').editable('show');
}, 500);
});
//create new user
$('#save-btn').click(function() {
$('.myeditable').editable('submit', {
url: '/newuser',
ajaxOptions: {
dataType: 'json' //assuming json response
},
success: function(data, config) {
if(data && data.id) { //record created, response like {"id": 2}
//set pk
$(this).editable('option', 'pk', data.id);
//remove unsaved class
$(this).removeClass('editable-unsaved');
//show messages
var msg = 'New user created! Now editables submit individually.';
$('#msg').addClass('alert-success').removeClass('alert-error').html(msg).show();
$('#save-btn').hide();
$(this).off('save.newuser');
} else if(data && data.errors){
//server-side validation error, response like {"errors": {"username": "username already exist"} }
config.error.call(this, data.errors);
}
},
error: function(errors) {
var msg = '';
if(errors && errors.responseText) { //ajax error, errors = xhr object
msg = errors.responseText;
} else { //validation error (client-side or server-side)
$.each(errors, function(k, v) { msg += k+": "+v+"<br>"; });
}
$('#msg').removeClass('alert-success').addClass('alert-error').html(msg).show();
}
});
});
//reset
$('#reset-btn').click(function() {
$('.myeditable').editable('setValue', null)
.editable('option', 'pk', null)
.removeClass('editable-unsaved');
$('#save-btn').show();
$('#msg').hide();
});
});
</script>
And this is the html
<tr>
<td>adel</td>
<td></td>
<td></td>
<td></td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
<tr>
<td>sdqsd</td>
<td></td>
<td></td>
<td></td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
<tr>
<td>dzadz</td>
<td>from me with love</td>
<td>anywhere</td>
<td>http://justawebsite.com</td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
Now everything works fine, Except if I edit one of the 2 first rows and hit Ok It will send the details of the last form http://justawebsite.com and sometimes it doesn't send anything, It is really messed up and I spent hours reading te documentation but I couldn't figure out the problem
As I said in my comment, you've got different elements with the same id, so the selectors won't work (id must be unique). Put them as class instead:
<tr>
<td>
adel
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
<a href="#" class="myeditable picture" data-type="text" data-name="picture" data-original-title="Enter Picture">
<img src="" />
</a>
</td>
<td width="10%">
<button class="btn btn-primary btn-sm save-btn">Ok</button>
<button class="btn btn-sm pull-right reset-btn">Reset</button>
</td>
</tr>
Here's a fiddle to get you started https://jsfiddle.net/virginieLGB/k2of9xor/1/
On there, you'll see that I've selected the editable elements you want to submit.
$('.save-btn').click(function() {
var that = $(this);
var allEditables = that.parents("tr").find(".myeditable"); // all ".myeditable" elements in the same "tr" as the ".save-btn" that was clicked on
allEditables.each(function() {
// here I've kept your code because I don't know what happens in your file, but maybe you need a bulk action
$(this).editable('submit', {
...
I don't know how your PHP file works, so don't know how you save your user and if you need to submit all fields at once or not. If so, you'll have to modify my answer a bit.
Have you tried refreshing it afterwards?
For me i noticed, that as soon as it was refreshed i got the result that i have been expecting, but only for one of them. However, i couldn't solve the problem yet.
Please let me know what kind of result you get.
Otherwise try debugging...disable one of the first rows and try it again..
I am working with jQuery Sortable and twitter bootstrap as well. I have table rows that I am trying to sort. The drag and drop is working fine but I am trying to send the new sort order via ajax which is not picking up/sending the sort order and when i try to alert the data it seems empty.
This is my PHP code which is using loop to pull the records from MySQL
<table class="table table-striped table-bordered ">
<thead>
<tr>
<th> Slide Title</th>
<th> Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
?>
<tr id="<?php echo $row['id']; ?>">
<td>
<?php echo $row['title']; ?>
</td>
<td>
<div class="btn-group pull-right">
<button data-toggle="dropdown" class="btn btn-small btn-info dropdown-toggle">
Action<span
class="caret"></span></button>
<ul class="dropdown-menu">
<li>Edit
</li>
<li>
Delete
</li>
</ul>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
and this is the java script that is doing the sorting and then sending data to a file called slides.php
$(document).ready(function(){
$(function() {
$('table').sortable({
items: 'tr',
opacity: 0.6,
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
alert(data);
$.ajax({
data: data,
type: 'POST',
url: 'slides.php'
});
}
});
});
});
What I feel is my variable data var data = $(this).sortable('serialize'); is not working, if i send a static variable then I am able to see that in $_POST
I will really really appreciate any assistance in this.
I ended up following up the concept mentioned on this link to do my task, for some reason current solution was not working with <table> so I just re wrote the html part using <ul></ul> and it worked.
I hope this helps anyone out there having the same problem.