I trying to addClass to a row $('tr:first-child').next().addClass("current");
Entire html
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>All Rows</title>
<script type="text/javascript" src="jquery.js"></script>
<style type="text/css">
.container {padding-left: 20px; padding-right: 20px;}
.forms{
display:inline-block;
margin-top:2%;
}
.buttons{border:1px solid #708090;}
input {margin-bottom:2%;margin-right:5%;}
button{margin-right:3%;}
.forms{border-top:3px solid #708090;}
.tableholder{height:300px; overflow-y:auto;}
.current{background-color:pink;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$.get("getall.php", function(data){
{
$('.tableholder').append(data);
}
});
$('tr:first-child').next().addClass("current");
$("#next").click(function(){
$("table").find('.current').removeClass("current");
});
});
</script>
</head>
<body>
<div id="sc" class="container">
<div class="tableholder">
</div>
</div>
</body></html>
and my php script.Don't worry about the deprecated mysql functions.We use an old php installation
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "caliban";
$tableName = "caliban";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_assoc($result);
$result = mysql_query("SELECT * FROM $tableName");
$rows = Array();
$i=0;
while($row = mysql_fetch_assoc($result)){
//array_push($rows, $row);
$rows[$i++] = $row;
}
echo "<table id='tab' border='1'>
<thead>
<tr>
<th><form><input type='checkbox' /></form></th>
<th>firstname</th>
<th>lastname</th>
<th>city</th>
<th>continent</th>
</tr>
</thead>
<tbody>";
for($j=0;$j<count($rows); $j++){
$id = $rows[$j]['id'];
$firstname = $rows[$j]['firstname'];
$lastname = $rows[$j]['lastname'];
$city = $rows[$j]['city'];
$continent = $rows[$j]['continent'];
echo
"<tr id='$id' class=''>
<td><input type='checkbox' /></td>
<td>$firstname</td>
<td>$lastname</td>
<td>$city</td>
<td>$continent</td>
</tr>";
}
echo "</tbody>
</table>";
?>
The get is successful and the table displays as it should but the class cannot be applied.Where am i going wrong?.
Try this:
$(document).ready(function () {
$.get("getall.php", function (data) {
$('.tableholder').append(data);
$('tr:first-child').next().addClass("current");
});
$("#tab").on('click','#next',function () {
$("table").find('.current').removeClass("current");
});
});
BTW,IDs must be unique on context page, that means only one element can have the ID 'next'
Here is your code block.
$(document).ready(function(){
$.get("getall.php", function(data){
{
$('.tableholder').append(data);
}
});
$('tr:first-child').next().addClass("current");
The $.get call is asynchronous which means, the script will continue before it's results are returned. Thus,
$('tr:first-child').next().addClass("current");
Is getting called before,
$('.tableholder').append(data);
Try this instead:
$(document).ready(function(){
$.get("getall.php", function(data){
{
$('.tableholder').append(data);
$('tr:first-child').next().addClass("current");
}
});
Your .get() request is asynchronous, so when you're trying to apply that style, there is no table yet. Apply the style after you append the data.
$.get("getall.php", function(data) {
$('.tableholder').append(data);
$('tr:first-child').next().addClass("current");
});
Related
I have one table fetching data from database and displaying on page using PHP. i have created pagination using Ajax,PHP and MySQL. but when i am clicking on the page numbers, some time it is working and some time the table is displaying records on the first page irrespective of the page i clicked.please help me to solve this issue, i am trying since long time to resolve the issue and i could not. My main page is as follows.....
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Load Data without page refresh</title>
<!--<link rel="stylesheet" href="style/css/bootstrap.min.css">-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<!--<script src="scripts/js/bootstrap.min.js"></script>-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!--<script src="scripts/js/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Pagintation without page refresh</h3>
<div class="table-responsive" id="pagination_data">
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
load_data();
function load_data(page) {
$.ajax({
url: "pagination.php",
method: "POST",
data: {
page: page
},
success: function(data) {
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function() {
var page = $(this).attr("id");
//alert(page);
load_data(page);
});
});
</script>
pagination.php
<?php
//pagination.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$record_per_page = 5;
$page = '';
$output = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM tbl_student ORDER BY student_id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["student_name"].'</td>
<td>'.$row["student_phone"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM tbl_student ORDER BY student_id DESC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>
I try to make some reorder with drag and drop with PHP and some ajax with this tutorial.
I set up my files for my needs but nothing going on.
On my index.php just change this thing that equal to my MySQL
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>">
<td><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
Here is Java script in index.php:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
var selectedData = new Array();
$('.row_position>tr').each(function() {
selectedData.push($(this).attr("id"));
});
updateOrder(selectedData);
}
});
function updateOrder(data) {
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:data},
success:function(){
alert('your change successfully saved');
}
})
}
</script>
</html>
Here is and ajaxPro.php that i change:
require('db_config.php');
$position = $_POST['position'];
$i=1;
foreach($position as $k=>$v){
$sql = "Update `channels` SET `channel_number`=".$i." WHERE `id`=".$v;
$mysqli->query($sql);
$i++;
}
And here is MySQL
When I try to reorder, just want to change field channel_number but nothing goings-on. Where is my mistake
I've change some code, and turn on some log, but still have problem. If anyone can assist will be so happy. Here it is:
index.php
<div class="container">
<h3 class="text-center">Dynamic Drag and Drop table rows in PHP Mysql - ItSolutionStuff.com</h3>
<table id="myTable" class="table table-bordered">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">#</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody class="row_position">
<?php
require('db_config.php');
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>"> <!-- data-channel-number="<?php echo $user['channel_number'] ?>">-->
<td><?php echo $user['id'] ?></td>
<td class="index"><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!-- container / end -->
</body>
<!--<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
//console.log(chArray);
}
});
</script>-->
<script>
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
},
updateIndex = function(e, ui) {
$('td.index', ui.item.parent()).each(function (i) {
$(this).text(i+1);
});
};
$("#myTable tbody").sortable({
distance: 5,
//delay: 100,
opacity: 0.6,
cursor: 'move',
helper: fixHelperModified,
update: function() {
var chArray = [];
$('.row_position>tr').each(function() {
chArray.push({
chid : $(this).attr("id"),
chnumber : $(this).closest('tr').find('td.index').text()
});
});
console.log(chArray);
// console.log(data);
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:chArray},
success:function(data){
console.log(data);
//alert('your change successfully saved');
},
error: function (error) {
// console.log(error);
}
})
},
stop: updateIndex
}).disableSelection();
</script>
</html>
ajaxPro.php
error_reporting(1);
require('db_config.php');
$data = $_POST['position'];
echo $data;
//$i=1;
foreach($data as $d){
echo $d['chnumber'];
$sql = "Update channels SET channel_number=".$d['chnumber']." WHERE id=".$d['chid'];
$mysqli->query($sql);
}
It's look good in browser everything is changed (if i move chanel from possition 4 to position 2 it's change on the screen to position 2, but in array chnumber is still 4, and i don't know how to change this.
Here is some pics.
1st order when you load page
Reorder when move channel from pos:4 to pos:2
And here is console log
this code,i have done searching through enroll number. All code are correct and running properly but when match data are not found. No message shown .so, i want to show a message when match data are not found like that "No Such Data Found".
How can i do this? please help to solve that problem,
My code is below.
index.php
<!DOCTYPE html>
<html>
<head>
<title>How to return JSON Data from PHP Script using Ajax Jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#result {
position: absolute;
width: 100%;
max-width:870px;
cursor: pointer;
overflow-y: auto;
max-height: 400px;
box-sizing: border-box;
z-index: 1001;
}
.link-class:hover{
background-color:#f1f1f1;
}
</style>
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">How to return JSON Data from PHP Script using Ajax Jquery</h2>
<h3 align="center">Search Employee Data</h3><br />
<div class="row">
<div class="col-md-4">
<input type="text" name="employee_list" id="employee_list" class="form-control">
</div>
<div class="col-md-4">
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
</div>
</div>
<br />
<div class="table-responsive" id="employee_details" style="display:none">
<table class="table table-bordered">
<tr>
<td width="10%" align="right"><b>Name</b></td>
<td width="90%"><span id="name"></span></td>
</tr>
<tr>
<td width="10%" align="right"><b>Address</b></td>
<td width="90%"><span id="address"></span></td>
</tr>
<tr>
<td width="10%" align="right"><b>Gender</b></td>
<td width="90%"><span id="total_marks"></span></td>
</tr>
<tr>
<td width="10%" align="right"><b>Designation</b></td>
<td width="90%"><span id="email"></span></td>
</tr>
<tr>
<td width="10%" align="right"><b>Age</b></td>
<td width="90%"><span id="ph"></span></td>
</tr>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#search').click(function(){
var enroll= $('#employee_list').val();
if(enroll != '')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{enroll:enroll},
dataType:"JSON",
success:function(data)
{
if(data.length != 0){
$('#employee_details').css("display", "block");
$('#name').text(data.name);
$('#address').text(data.address);
$('#total_marks').text(data.total_marks);
$('#ph').text(data.ph);
$('#email').text(data.email);
}
else { alert("Please Select Employee"); }
}
})
}
else
{
alert("Please Select Employee");
$('#employee_details').css("display", "none");
}
});
});
</script>
fetch.php
<?php
//fetch.php
if(isset($_POST["enroll"]))
{
$connect = mysqli_connect("localhost", "root", "", "aviation");
$query = "SELECT * FROM student WHERE enroll = '".$_POST["enroll"]."'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$data["name"] = $row["name"];
$data["address"] = $row["address"];
$data["total_marks"] = $row["total_marks"];
$data["email"] = $row["email"];
$data["ph"] = $row["ph"];
}
echo json_encode($data);
}
}
?>
In your PHP code, you seam to use a loop to fetch database rows. But your PHP Code acts like you only receive 1 row on data.
Ill consider for the moment that you only will get 1 row of data unless you specify otherwise.
You already check if mysql returns 1 or more results.
So, all we need is a variable that tells you if a results has been found.
Example:
<?php
$output = array(
'result' => 0
);
if (isset($_POST["enroll"])) {
$connect = mysqli_connect("localhost", "root", "", "aviation");
$query = "SELECT name,address,total_marks,email,ph FROM student WHERE enroll = '" . $_POST["enroll"] . "'";
$result = mysqli_query($connect, $query);
if (mysql_num_rows($result) == 1) {
$output['row'] = mysqli_fetch_array($result);
$output['result'] = 1;
}
}
echo json_encode($output);
Then, if your javascript code, you only have to test if the data.result is equal to 1 or 0 and act accordingly. Example:
<script>
$(document).ready(function () {
$('#search').click(function () {
var enroll = $('#employee_list').val();
if (enroll != '')
{
$.ajax({
url: "fetch.php",
method: "POST",
data: {enroll: enroll},
dataType: "JSON",
success: function (data)
{
if(data.result == 1){
$('#employee_details').css("display", "block");
$('#name').text(data.row.name);
$('#address').text(data.row.address);
$('#total_marks').text(data.row.total_marks);
$('#ph').text(data.row.ph);
$('#email').text(data.row.email);
}
else{
alert("No Such Data Found");
}
}
})
} else
{
alert("Please Select Employee");
$('#employee_details').css("display", "none");
}
});
});
</script>
Edit: be carefull, you should also sanitise the POST variable before using it in your mysql query
you could just add
error: function(){
alert('No Such Data Found!');
}
after the success:function(data)
so your ajax call would be like :
$.ajax({
url:"fetch.php",
method:"POST",
data:{enroll:enroll},
dataType:"JSON",
success:function(data)
{
if ($.trim(data)){
$('#employee_details').css("display", "block");
$('#name').text(data.name);
$('#address').text(data.address);
$('#total_marks').text(data.total_marks);
$('#ph').text(data.ph);
$('#email').text(data.email);}
else{alert('No Such Data Found!')}
},
error: function(){
alert('error !');
}
or add an else in your php code that return a false if result is empty :
if(mysql_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
//code ......
}
echo json_encode($data);
}else {
return false;
}
then your ajax call would be like :
$.ajax({
url:"fetch.php",
method:"POST",
data:{enroll:enroll},
dataType:"JSON",
success:function(data)
{
if(data != false){
$('#employee_details').css("display", "block");
$('#name').text(data.name);
$('#address').text(data.address);
$('#total_marks').text(data.total_marks);
$('#ph').text(data.ph);
$('#email').text(data.email);}else{alert('No Such Data Found!');}
}
I have problem with delete function. I am trying to delete specific row from table, to allow admin to delete row he wants, row with certain id. I think there is problem in my script with getting value of id.
With these two scripts, I get deleted all the values from table when I click on delete option in any row, so thats why I think that I am having problem with taking value of id. Still couldnt solve this by myself so I decided to ask you, do you maybe see something that I dont?
report.php is a page with table that includes all the rows from database table, here is the code:
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<style>
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid gray;
padding:5px;
}
tr:hover {background-color: #f5f5f5}
</style>
<head>
<body>
<?php
require_once '../include/functions.php';
require_once '../include/db.php';
$htmltable = "";
$htmltable .= "<table>
<tr>
<th>ID</th>
<th>Ime</th>
<th>Ime slavljenika</th>
<th>Datum</th>
<th>Poruka</th>
<th>Vreme prijave</th>
<th>Obrisi</th>
</tr>";
$prep = $db->prepare("SELECT * from prijavljeni");
$prep->execute();
$prijavljeni = $prep->fetchAll();
foreach($prijavljeni as $prijavljen => $row) {
$htmltable.= '<tr>
<td>'.$row['prijavljeni_id'].'</td>
<td>'.$row['ime'].' </td>
<td>'.$row['ime_slavljenik'].' </td>
<td>'.$row['datum'] .'</td>
<td>'.$row['poruka'].' </td>
<td>'.$row['vreme'].'</td>
<td>Delete</td>
</tr>';
}
$htmltable.='</table>';
echo $htmltable;
?>
<div>
<button onclick="return email()">Posalji</button>
<div id="emailporuka">
</div><br><br>
</div>
<p align="center">Logout</p>
<script>
function email(){
$.ajax({
type:"post",
url: "email.php",
success: function(data){
//window.alert(data);
document.getElementById("emailporuka").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
</body>
</html>
delete.php
<?php
include('../include/db.php');
include('../include/functions.php');
$prijavljeni_id=$_GET['prijavljeni_id'];
$result = $db->prepare("DELETE FROM prijavljeni WHERE prijavljeni_id = prijavljeni_id");//brise sve reove
$result->bindParam('prijavljeni_id', $prijavljeni_id);//brise sve redove
$result->execute();
header("location: izvestaj.php");
?>
You have issue in prepare statement
Change
$result = $db->prepare("DELETE FROM prijavljeni WHERE prijavljeni_id = prijavljeni_id");//brise sve reove
$result->bindParam('prijavljeni_id', $prijavljeni_id);
To
$result = $db->prepare("DELETE FROM prijavljeni WHERE prijavljeni_id = :prijavljeni_id");// Need to add : before bind param name//brise sve reove
$result->bindParam(':prijavljeni_id', $prijavljeni_id);
According to your code prijavljeni_id = prijavljeni_id so this condition become always true so your all records are being deleted
Also change <a> as below. add $row instead of $prijavljeni
<td>Delete</td>
What my application does is, loads a list of items into a table, via MySQL.
I can load the table fine, but I need to make it so the items in the table can be rearranged and their positions stored back into the MySQL server.
Here is the main page (workshops.php):
<?php
require_once("connection.php");
?>
<html>
<head>
<style type="text/css">
body { position: relative; }
#content { width: 742px; height: auto; position: relative; margin-left: auto; margin-right: auto; }
</style>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$(document).ready(function() {
var fixHelper = function(e,ui){
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
$("#sortable tbody.contenet").sortable({
helper: fixHelper,
stop: function(event, ui)
{alert("something changed");
//create an array with the new order
order = $.map($(this).find('input'), function(el){
for (j=0; j < $(el).length; j++){
return $(el).attr('id') + '=' + j;
}
});
var message = "";
for(i=0; i < order.length; i++){
message = message + order[i];
message = message + " ";
}
alert(message);
//sorder = order.serializeArray();
//alert(sorder);
$.ajax({
url: "updateworkshops.php",
type: "post",
data: order,
error: function (){
alert("theres an error with AJAX");
},
success: function(){
//alert("Saved.");
}
});
}
});
});
</script>
</head>
<body>
<div id="content">
<p>Click on "+ Create new workshop" to create a new workshop".</p>
<p>Click on the name of a workshop to add dates and times for when it is available and/or to make changes to it.</p>
<br />
<table>
<!--Create Workshop-->
<tr>
<td width="25%" bgcolor="6BF26B">+ Create new workshop</td>
</tr>
<tr><td bgcolor="FFFF00">~ Edit settings</td>
</tr></table><br />
<form id="pickles" action="updateworkshops.php" method="post">
<table id="sortable"><tbody class="contenet">
<!--List Workshops-->
<?php
$query = "SELECT * FROM workshops ORDER BY position";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo "<tr bgcolor='{$row['color']}'>"; echo "\r\n";
echo "<td><input type=\"hidden\" id=\"order_".$row['id']."\" name=\"order_".$row['id']."\" value=\"".$row['position']."\" /><label class=\"handle\">[X]</label></td>"; echo "\r\n";
echo "<td><a href='edit.php?workshop_id={$row['id']}'>{$row['name']}</a></td>"; echo "\r\n";
echo "<td>{$row['description']}</td>"; echo "\r\n";
echo "</tr>"; echo "\r\n";
}
?>
</tbody>
</table>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
</body>
</html>
<?php mysql_close(); ?>
And this is the updateworkshops.php page that it POST the data to:
<?php
require_once("connection.php");
if(isset($_POST['submit'])) {
while(list($key,$value) = each($_POST)){
if(substr($key,0,5) == "order_"){
$id = trim($key,'order_');
$sql = 'UPDATE workshops SET position = '.$value.' WHERE id = '.$id;
if(!mysql_query($sql)) {
echo "SOMETHING WENT WRONG";
}
}
}
}
mysql_close();
?>
When the table is done moving an item, I made it so it alerts the new array that it will POST to the updateworkshops.php page. When I do that, all the order_#'s are equal to 0 and those values are not stored in the database.
I feel like I'm missing something, but I've been trying to fiddle with this code for the past couple hours. Maybe it doesn't help that I'm unfamiliar with Javascript... but I thought I have the right idea down.
Try doing something like this:
var sortable = $("#sortable tbody.contenet").sortable({
helper: fixHelper,
stop: function(event, ui) {
//create an array with the new order
order = $(this).find('input').map(function(index, obj) {
var input = $(obj);
input.val(index + 1);
return input.attr('id') + '=' + (index + 1);
});
$.ajax({
url: "updateworkshops.php",
type: "post",
data: order,
error: function() {
console.log("theres an error with AJAX");
},
success: function() {
console.log("Saved.");
}
});
}
});
All you need to do is use map to loop over the inputs use the index of the loop as the order. This code also updated the input value to have the new position value.
Also its time to learn about firebug or webkit developer tools and console.log rather than using alert. Alert is not a debug tool.