sending jQuery sortable data via ajax - javascript

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.

Related

How can I pass an ID from selected table row to my AJAX function that fetching data

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>

Refresh table which contain a php code

I have a PHP code, which is in a table tag.It shows a text from database. I want to refresh this table, to load updated text from database in every - let's say - 1 minute without refreshing the whole page. I've found several solutions to reload table without refreshing a page and it seems it can be done with AJAX or JS, but they only refresh it with a specific content or a specific file, however, I can't figure out how to refreshed.
<table class="table table-striped">
<thead>
<tr>
<th>Department</th>
<th class="col_small col_center">Employees</th>
<th class="col_small col_center">% Percentage</th>
</tr>
</thead>
<tbody>
<?php $employeeslist=$emp_departmentObj->selectorgall();
foreach($employeeslist as $list)
{
$total=$emp_regObj->selectorgall();
$totalemp=count($total);
$deptemp=$emp_regObj->selectemployee($list->id);
$totaldeptemp=count($deptemp);
$percentage=($totaldeptemp/$totalemp)*100;
?>
<tr>
<td><?php echo $list->department ?></td>
<td class="col_center">
<?php echo $totaldeptemp; ?>
</td>
<td class="col_center">
<?php echo number_format($percentage,1).'%'; ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
You can define a function in document ready like this
$(document).ready(function() {
setInterval(function() { rebindTable() }, 3000);
function rebindTable() {
$.ajax({
url: "http://localhost:80/data.php",
success: function(result) {
var data = result;
$('#td-1-data').html(data.param1);
$('#td-2-data').html(data.param2);
}
});
}
})
this way you can use an setInterval method and re-bind the data in the table using ajax , in this i assume your http://localhost:80/data.php is returning some data which your are binding to the td of the table you have defined

Retrieve a specific row value from table HTML and submit it to PHP

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/

JQuery DataTables and Jeditable - fields contains html but should not. Why?

I am using DataTables and Jeditbale. Everything seems to work well, however, for some reason when I double-click any field within the table, it contains HTML. I have inserted the visual herein. I have not tried anything to fix this problem as I cannot even understand how this would occur. I have googled the problem but most people who report a similar problem just report extra blank spaces; not full html in fields. How can I fix this? If additional code required, can add in due course.
Here is my table code:
<!-- start table listing -->
<table id="myTable" class="stripe hover cell-border row-border">
<thead>
<tr>
<th id="country_id">Country ID</th>
<th id="country">Country Name</th>
<th id="country_import">Import Commnents</th>
<th id="country_export">Export Comments</th>
<th id="country_date_created">Created</th>
<th id="country_date_updated">Updated</th>
<th id="">Updated by</th>
<th id="country_enabled">Enabled?</th>
<th id="">Actions</th>
</tr>
</thead>
<tbody>
<?php
foreach ($query as $row ) {
?>
<tr <?php echo 'id="'.$row->country_id.'"'; ?> >
<td>
<?php echo $row->country_id; ?>
</td>
<td>
<a class='table-action-deletelink' href='/admin/country_view/<?php echo ''.$row->country_id.''; ?> '><?php echo $row->country; ?></a>
</td>
<td>
<?php echo $row->country_import_comments; ?>
</td>
<td>
<?php echo $row->country_export_comments; ?>
</td>
<td>
<?php echo $row->country_date_created; ?>
</td>
<td>
<?php echo $row->country_date_last_updated; ?>
</td>
<td>
<?php echo $row->country_updated_by; ?>
</td>
<td> <?php
if ($row->country_enabled == 1) {
echo '<span class="glyphicon glyphicon-ok" aria-hidden="true" ></span>';
} else {
echo '<span class="glyphicon glyphicon-remove" aria-hidden="true" ></span>';
} ?>
</td>
<td>
<!-- main container -->
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="/admin/country_view/<?php echo ''.$row->country_id.''; ?>">View</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Edit</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Deactivate</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="/admin/country_delete/<?php echo ''.$row->country_id.''; ?> ">Delete</a></li>
</ul>
</div>
</td>
</form>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
Here is my javascript that implements the table:
$(document).ready(function() {
//sDeleteURL: "/Home/DeleteData.php"
$('#myTable').dataTable().makeEditable( {
// some basic config
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': "admin/json_get_countries",
stateSave: true,
"scrollCollapse": true,
"language": {
"lengthMenu": "Display _MENU_ records per page",
"zeroRecords": "Nothing found - sorry",
"info": "Showing page _PAGE_ of _PAGES_",
"infoEmpty": "No records available",
"infoFiltered": "(filtered from _MAX_ total records)"
}
} );
} ); // end of on doc load
You're using jQuery DataTables Editable plugin which internally uses jQuery Jeditable plugin.
According to Jeditable documentation (see Usage with Textile, Markdown, ReST, WiKi), if field contains content other than plain text (HTML, Markdown, etc), you need to use loadurl parameter to load content in and sUpdateURL to save modified value.
See Editable DataTable example - custom editors on how Engine version field is being edited and saved by using URLs specified in loadurl and sUpdateURL parameters.
You can make certain columns read-only and not-editable by defining aoColumns option and specifying null for corresponding column. aoColumns is an array holding options for all columns in sequential order, length of this array must be equal to the number of columns in the original HTML table.
Example:
$(document).ready( function () {
$('#example').dataTable().makeEditable({
sUpdateURL: "UpdateData.php",
"aoColumns": [
null,
{
},
{
indicator: 'Saving platforms...',
tooltip: 'Click to edit platforms',
type: 'textarea',
submit:'Save changes',
fnOnCellUpdated: function(sStatus, sValue, settings){
alert("(Cell Callback): Cell is updated with value " + sValue);
}
},
{
//indicator: 'Saving Engine Version...',
tooltip: 'Click to select engine version',
loadtext: 'loading...',
type: 'select',
onblur: 'cancel',
submit: 'Ok',
loadurl: 'EngineVersionList.php',
loadtype: 'GET',
sUpdateURL: "CustomUpdateEngineVersion.php"
},
{
indicator: 'Saving CSS Grade...',
tooltip: 'Click to select CSS Grade',
loadtext: 'loading...',
type: 'select',
onblur: 'submit',
data: "{'':'Please select...', 'A':'A','B':'B','C':'C'}",
sUpdateURL: function(value, settings){
alert("Custom function for posting results");
return value;
}
}
]
});
})
See answer to similar problem with Jeditable. However this answer targets Jeditable only and not jQuery DataTables Editable plugin, so the code shown there doesn't apply, just the explanation.

deleting entire row with jquery json ajax php

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);
}

Categories

Resources