This is my table which is dynamic, with this I am getting three tables with different ids.
<?php
echo "<table class='table table-hover table-bordered' ondrop='drop(event,this)' ondragover='allowDrop(event)' id='".$type."'>";
if(empty($players))
echo "<tr><td></td></tr>";
foreach($players as $p)
{
echo "<tr data-id='".$p['to']."' data-fixture='".$p['fixture']."' data-team='".$p['team']."' draggable='true' ondragstart='drag(event,this)' id='".$type."aa'>";
echo "<td >".$p['name']."</td>";
echo "</tr>";
}
echo "</table>";
?>
My Javascript is this:
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev,str) {
//alert(str);
var temp = str.parentNode;
child = temp.children;
if(child.length==1)
{
$(temp).append("<tr><td></td></tr>");
}
ev.dataTransfer.setData("text", ev.target.id);
ev.dataTransfer.setData("val", ev.target.getAttribute('data-id'));
ev.dataTransfer.setData("fixture", ev.target.getAttribute('data-fixture'));
ev.dataTransfer.setData("team", ev.target.getAttribute('data-team'));
}
function drop(ev,str) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
var id = ev.dataTransfer.getData("val");
var fixture = ev.dataTransfer.getData("fixture");
var team = ev.dataTransfer.getData("team");
ev.target.appendChild(document.getElementById(data));
//alert(fixture);
if(str.id=='avl')
status=1;
else if(str.id=='uavl')
status=2;
$.ajax({
url: "<?php echo base_url();?>index.php/teams/update_players/"+status+"/"+id+"/"+fixture+"/"+team,
type: 'GET',
success: function(data) {
//$("#a_p").html(data);
//alert(data);
},
});
}
when dropping table rows from one table to another.. tr got dropped to td not in table.
like this
<table>
<tr>
<td>
<tr> (this is a dropped row)
<td></td>
</tr>
</td>
</tr>
</table>
Your drop function appends a child to ev.target. Try using console.log to check the tagName for ev.target. If it's TD, then that's your problem.
Not providing this in the comment section, because I don't have enough reputation for submitting comments.
Related
I have this code in which I am trying to show and hide the data on clicking a product number and the data is being fetched from database through AJAX. I want the data to be shown beneath the desired row. I want to put the data in tbody and show it on clicking its product number.
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
?>
<tr><td align="center"><?php echo $row['FONumber']; ?></td></tr>
<tbody id='sd'<?php echo $p; $p++; ?>></tbody>
<?php }
}
Javascript and AJAX:
$(function(){
$('#hover1').on({
mouseenter:function(){$(this).css("background","grey")},
mouseleave:function(){$(this).css("background","white")}},'tr');
});
// number of tds
var c = $('#hover1').find('td').length;
var id = document.getElementById("hover1");
for(var i = 0; i < c; i++){
id.rows[i].onclick=(function(){
var a = $(this).find('td:eq(0)').text();
$.ajax({
url: 'printpo1.php',
type: 'post',
data: {fo:a},
success: function(data){
$('#name').html(data);
}
});
$('#sd'+i).toggle();
alert('#sd'+i);
});
}
So far the data I am trying to fetch is showing in the tbody of the first row. Any help will be really appreciated.
I am trying some things regarding Ajax, Jquery and PHP.
My JavaScript code (the pop.php is located correctly)
<script type="text/javascript">
$('.nameclick').click(function()) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id=$(this).data("formid")}
success: function(result){
alert(result);
} else {
alert("test");
}
});
});
</script>
Part of my html/php code in the same page (this code works fine to print out the table I am looking for):
<table class="data-table">
<thead>
<tr>
<th>Servicenummer</th>
<th>Kund</th>
<th>Uppgift</th>
<th>Status</th>
<th>Inlämnad</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td><div id="clickMe">'.$row['service'].'</div></td>
<td>'.$row['name'].'</td>
<td>'.$row['Drakt1'].'<br>'.$row['Drakt2'].'<br>'.$row['Drakt3'].'<br>'.$row['Drakt4'].'<br>'.$row['Drakt5'].'<br>'.$row['Drakt6'].'<br>'.$row['reg1'].'<br>'.$row['flaska1'].'<br>'.$row['dator1'].'</td>
<td>'.$row['Service_Status'].'</td>
<td>'.$row['date'].'</td>
</tr>';
$no++;
}?>
</tbody>
</table>
And my pop.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$telephone = $conn->real_escape_string($_POST['telephone']);
$sql = 'SELECT name, email, telephone FROM Service_Form WHERE id = "10"';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<?php
while ($row = mysqli_fetch_array($query))
{
echo $row['name'];
echo $row['email'];
echo $row['telephone'];
}
?>
At the moment when I click my link in my normal page I don't get anything, no alerts at all, but my pop.php prints out the values correctly, I hope... I know I have to change my id="10" to something but i am not certain to what, could it be formid?
What am I doing wrong here?
What I want:
a table with the values below from a table in the database
when I click the name in the table it should show an alert (or something similar) that shows the name, email and telephone number (these are stored as well in the database table but not on the website table).
your ajax function is having some errors
so use this
<script type="text/javascript">
$('.nameclick').click(function(ev) {
ev.preventDefault();
var id = $(this).data("formid");
$.ajax({
type: "POST",
url: "pop.php",
data: {
"id":id
},
success: function(result){
alert(result);
},
error:function (error) {
alert(error);
}
});
});
</script>
I am editing your jquery part please try
<script type="text/javascript">
$('.nameclick').click(function(ev)) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id:$(this).attr("data-formid")}
success: function(result){
if(result){
alert(result);
} else {
alert("test");
}
}
});
});
</script>
This is my index.php view were my table is placed
<table class="striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Address</th>
<th>Created at</th>
</tr>
</thead>
<tbody id="showdata">
<!--<tr>
<td>1</td>
<td>Alvin</td>
<td>Eclair</td>
<td>$0.87</td>
<td>
Edit
Delete
</td>
</tr>-->
</tbody>
</table>
This my ajax script placed on index.php
function showAllEmployee() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url(); ?>index.php/Employee/showAllEmployee',
async: false,
dataType: 'json',
success: function(data) {
//console.log(data);
var html = '';
var i;
for (i=0; i<data.length; i++) {
html += '<tr>'+
'<td>'+data[i].emp_id+'</td>'+
'<td>'+data[i].name+'</td>'+
'<td>'+data[i].address+'</td>'+
'<td>'+data[i].created_at+'</td>'+
'<td>'+
'Edit'+
'Delete'+
'</td>'+
'</tr>';
}
$('#showdata').html(html);
},
error: function() {
alert('Could not get data from database');
}
});
}
This is what i have on my employee controller
public function showAllEmployee()
{
$result = $this->em->showAllEmployee();
echo json_encode($result);
}
This is my model
public function showAllEmployee()
{
$this->db->order_by('created_at', 'desc');
$query = $this->db->get('tbl_employees');
if($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Whenever i refresh the page the data wont display instead i run into an error could not get the data from the database which is the condition i set on my ajax script what could be wrong pls help
set header as JSON type in the controller
change your controller to
public function showAllEmployee(){
$result = $this->em->showAllEmployee();
$this->output
->set_content_type('application/json')
->set_output(json_encode($result));
}
I need to update a row of a table. So when I click on a cell, I want it to be transformed into text box, so I used this:
<td contenteditable></td>
And then, when the content of a <td> is changed, I need to send it through AJAX to update it in the server without clicking on a button, so it will use the .change(function()).
I tried to get the content changed into a variable:
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = '<?php echo $row['id'] ?>';
var name = $("#emp_name").val();
var position = $("#position").val();
var salary = $("#salary").val();
$.ajax
({
url: 'update.php',
type: 'POST',
data: {dataId: rowid, data1: name, data2: position, data3: salary},//Now we can use $_POST[data1];
dataType: "text",
success:function(data)
{
if(data=="success")
{
//alert("Data added");
$("#before_tr").before("<tr><td>"+emp+"</td><td>"+pos+"</td><td>"+sal+"</td></tr>");
$("#emp_name").val("");
$("#position").val("");
$("#salary").val("");
}
},
error:function(data)
{
if(data!="success")
{
alert("data not added");
}
}
});
});
The problem is how to know which row is changed to send it via AJAX ? I am not getting any errors even when data not updated.
Here is the update.php code:
try
{
$rowid = $_POST['dataId'];
$emp_name = $_POST['data1'];
$pos = $_POST['data2'];
$sal = $_POST['data3'];
$upd = "UPDATE emp SET name = :emp_name, position = :pos, sal = :sal WHERE id = :rowid";
$updStmt = $conn->prepare($upd);
$updStmt->bindValue(":rowid", $rowid);
$updStmt->bindValue(":emp_name", $emp_name);
$updStmt->bindValue(":pos", $pos);
$updStmt->bindValue(":sal", $sal);
$updStmt->execute();
echo "success";
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
HTML:
<tbody>
<?php
$sql = "SELECT * FROM employee";
$stmt=$conn->prepare($sql);
$stmt->execute();
$res=$stmt->fetchAll();
foreach($res as $row){
?>
<tr id=""<?php echo $row['id'] ?>"">
<td contenteditable><?php echo $row['emp_name'] ?></td>
<td contenteditable><?php echo $row['position'] ?></td>
<td contenteditable><?php echo $row['salary'] ?></td>
</tr>
<?php } ?>
When loading your data with PHP you need to keep the row id in your html:
<tr id="<?php echo $yourList["id"]; ?>">
<td contenteditable></td>
</tr>
Then in your javascript you can catch it using the parent() jquery function
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid =$(this).parent().attr("id");
......
UPDATE
Check this example, I have added listeners to detect contenteditable td changes, I think you shall add it too , refer to this contenteditable change events for defining proper change events on contenteditable fields.
Explanation:
The contenteditable does not trigger change events, this work around is used to detect the focus event of the td using jquery on method and event delegation. The original content is saved in the td jquery data object $this.data('before', $this.html()); . Then when the user leaves the field or triggers any of the events 'blur keyup paste input', the current content is compared to the content in the data object, if it differs, the change event of the td is triggered.
$(document).ready(function(){
$('table').on('focus', '[contenteditable]', function() {
var $this = $(this);
$this.data('before', $this.html());
return $this;
}).on('blur keyup paste input', '[contenteditable]', function() {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
return $this;
});
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = $(this).parent().attr("id");
$("#res").html(rowid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="500px">
<tr id="1222">
<td contenteditable></td>
</tr>
<tr id="55555">
<td contenteditable></td>
</tr>
</table>
Row Id : <span id="res"></span>
<tr row_id="<?php echo $row['id'] ?>"> ></tr>
In Your Ajax
var rowid = $(this).attr('row_id');
I am trying to add a new row to the existing table using Ajax, PHP and Jquery.
Ajax call is successful (tested it by placing alerts). But it displays the new row only if I refresh the entire page. I want the row to be added to the table with out refreshing the entire page, but just with a table refresh on the fly.
example : As I press Add button on the table, it should add a new row to the table on the fly.
hotTopics_focusAreas_data.php file :
<?php
$SQL = "select * from hottopics order by id desc limit 1";
while($row = mysql_fetch_array($SQL,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
Javascript file :
$("document").ready(function() {
hotAddClicked();
});
function hotAddClicked(){
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table").append(data);
}
});
});
}
Table definition:
<table class="table" id="hottopics_table">
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$SQL = "select * from hottopics;";
$result_update = mysql_query($SQL) or die("Couldn't execute query.".mysql_error());
while($row = mysql_fetch_array($result_update,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
</tbody>
</table>
$(document).ready(function() {
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table tbody").append(data);
}
});
});
});
Check this jQuery script and check if it works properly.