How to load an editable table with AJAX - php

My site uses AJAX to load menus without having to refresh the page. For future reference, the main php file that contains all the menus is the index.php file. One of these menus has an editable table, which uses AJAX, jQuery and Datatable plugin. All the menus seem to load correctly, but the table doesn't load upon the first click, and then after it does load, it acts wrong; I try to add a single record, but it adds a random number of the record instead (for example, like 16 records). Also, for some reason, the appearance of the table changes; it's normal if the script source (the script being the Datatable script) is a cdn link, however it's messed up a bit if the source is a file (even though the file has the same code, except for the names of buttons and etc shown being in Hungarian, instead of English). None of the listed problems happen if the table's menu is loaded normally, without AJAX, but loading it with AJAX just messes it up, and I have no clue why.
Table after the first click on the Autok button
This is how the table looks by default
Table after adding only one record
As you can see, even though I added just one record (the one with test1), it got inserted 6 times... also, everything on the site just doubled; double search bars, buttons, etc... before I added the test1 record, there really were only 9 entries, so it appears, the 9 entries text remained from before the record was added, and above that the new, 15 entries text was loaded. So, my question is: how do I make it, so that only that one records I actually inserted gets inserted (and not with a random number of copies)? Also, how do I get rid of the double search bars and such after insertion, and how do I make it, so that the table properly displays even after the first click on the Autok button on the left?
I tried using a newer jQuery and Database sourcecode, but it didn't do anything. I also tried to remove the $(document).ready(function()... parts of the code, either only from the index.php file, or from the autok.php file, but neither worked. As I mentioned before, if the table's menu is loaded without AJAX, everything works like a charm (the table itself still operates with AJAX), but I need it to load with AJAX, so I want to fix this. As for the database (MySQL), everything refreshes and works as it should, though for some reason I can't seem to delete the records that were wrongly inserted multiple times, because even if I click on delete (within phpmyadmin, it just... stays there.
This makes the table's menu (autok, which gets its content from autok.php) load without refreshing any pages, by clicking on its button (button's ID is autok), and then loading the table in a large div (which has the cell-content ID).
This is the code responsible for loading the Autok menu, it's found in my index.php file (just ignore the "belépés" and "regisztráció" parts, those work differently, not with AJAX):
<div id="menuk" class='belso bal'>
<?php
if(empty($_SESSION["username"]))
{
echo"<a href='?p=belep' >Belépés</a>";
}
else
{
echo"<a href='autok.php' id='autok'>Autók</a>";
echo"<a href='alkalmazottak.php' id='alkalmazottak'>Alkalmazottak</a>";
echo"<a href='vevok.php' id='vevok' >Vevők</a>";
}
echo"<a href='?p=reg'>Regisztráció</a>";
?>
</div>
<div id="cell-content" class='belso jobb' >
<script>
$(document).ready(function(){
$("#autok").click(function(){
$("#cell-content").load('autok.php');
return false;
});
});
$(document).ready(function(){
$("#alkalmazottak").click(function(){
$("#cell-content").load('alkalmazottak.php');
return false;
});
});
$(document).ready(function(){
$("#vevok").click(function(){
$("#cell-content").load('vevok.php');
return false;
});
});
</script>
This is the Autok menu's php (autok.php):
<html>
<head>
<title>Autószalon</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<style>
#user_data {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#user_data td, #user_data th {
border: 1px solid #ddd;
padding: 8px;
}
#user_data tr:nth-child(even){background-color: #f2f2f2;}
#user_data tr:hover {background-color: #ddd;}
#user_data th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<h1 align="center">Autószalon</h1>
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" name="add" id="add" class="btn btn-info">Hozzáad</button>
</div>
<br />
<div id="alert_message"></div>
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Autó</th>
<th>Ár</th>
<th>Alkalmazott</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
fetch_data();
function fetch_data()
{
var dataTable = $('#user_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch.php",
type:"POST"
}
});
}
function update_data(id, column_name, value)
{
$.ajax({
url:"update.php",
method:"POST",
data:{id:id, column_name:column_name, value:value},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
$(document).on('blur', '.update', function(){
var id = $(this).data("id");
var column_name = $(this).data("column");
var value = $(this).text();
update_data(id, column_name, value);
});
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="data1"></td>';
html += '<td contenteditable id="data2"></td>'
html += '<td contenteditable id="data3"></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs">Beszúrás</button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html);
});
$(document).on('click', '#insert', function(){
var auto = $('#data1').text();
var ar = $('#data2').text();
var alkalmazott = $('#data3').text();
if(auto != '' && ar != '' && alkalmazott !='')
{
$.ajax({
url:"insert.php",
method:"POST",
data:{auto:auto, ar:ar, alkalmazott:alkalmazott},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
else
{
alert("Egy mezot kihagyott!");
}
});
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
if(confirm("Biztosan torolni szeretne?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
success:function(data){
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
});
});
</script>
As for the referenced PHPs, here is my fetch.php code:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if (!mysqli_connect_errno() && mysqli_set_charset($connect, "utf8"))
{
$columns = array('ID', 'Auto', 'Ar', 'Alkalmazott');
$query = "SELECT * FROM automenu ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE auto LIKE "%'.$_POST["search"]["value"].'%"
OR alkalmazott LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'
';
}
else
{
$query .= 'ORDER BY id DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="Auto">' . $row["Auto"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="Ar">' . $row["Ar"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["id"].'" data-column="Alkalmazott">' . $row["Alkalmazott"] . '</div>';
$sub_array[] = '<button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row["id"].'">Törlés</button>';
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM automenu";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
}
?>
Here is the update.php:
<?php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if (!mysqli_connect_errno() && mysqli_set_charset($connect, "utf8"))
{
if(isset($_POST["id"]))
{
$value = mysqli_real_escape_string($connect, $_POST["value"]);
$query = "UPDATE automenu SET ".$_POST["column_name"]."='".$value."' WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $query))
{
echo 'Adat Frissitve';
}
}
}
?>
Here is the insert.php:
<?php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if (!mysqli_connect_errno() && mysqli_set_charset($connect, "utf8"))
{
if(isset($_POST["auto"], $_POST["ar"], $_POST["alkalmazott"]))
{
$auto = mysqli_real_escape_string($connect, $_POST["auto"]);
$ar = mysqli_real_escape_string($connect, $_POST["ar"]);
$alkalmazott = mysqli_real_escape_string($connect, $_POST["alkalmazott"]);
$query = "INSERT INTO automenu(auto, ar, alkalmazott) VALUES('$auto', '$ar', '$alkalmazott')";
if(mysqli_query($connect, $query))
{
echo 'Adat Elmentve';
}
}
}
?>
And here is the delete.php code:
<?php
$connect = mysqli_connect("localhost", "root", "", "autoszalon");
if(isset($_POST["id"]))
{
$query = "DELETE FROM automenu WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $query))
{
echo 'Adat Torolve';
}
}
?>

Related

PHP/Ajax page navigation url change

Ik want to build a ajax/jquery page navigation so when the user clicks on a page, the url changes to so that there are no problems with browser's back button. I found a lot of answers for this but not what I searched for. I saw this code below on a tutorial site and I want to customize it so that the url moves to. Do I have to build that in the ajax script of on the PHP side? How can I achieve this?
My index.php
<html>
<head>
<title>Webslesson Tutorial | Make Pagination using Jquery, PHP, Ajax and MySQL</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Make Pagination using Jquery, PHP, Ajax and MySQL</h3><br />
<div class="table-responsive" id="pagination_data">
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(page)
{
$.ajax({
url:"pagina.php",
method:"POST",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
history.pushState({ foo: 'bar' }, '', '/bank'); // I tried this line but it don't work
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
And my pagina.php
<?PHP
$connect = mysqli_connect("hidden", "hidden", "hidden","publiek2") or die("Connection failed: " . mysqli_connect_error());
$record_per_page = 50;
$page = '';
$output = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC 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["merk"].'</td>
<td>'.$row["model"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC";
$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;
?>
Thanks in advance.
I've tried to customize the ajax script.
As a javascript and PHP developer I don't understand much about Jquery but I think the code describes that there is a div called.pagination_link takes id as page number eg: 1. And makes an HTTP POST request to the PHP side. You can simply do this with a sample example in Javascript.
HTML
<div id="1" classname="pagination_link">1</div>
Javascript
const id = document.querySelector('.pagination_link').getAttribute('id');
fetch('pagina.php', {
method : 'POST',
body : id
})
If you want to send data.
I added a hidden text value with the page number as value and called the id 'idd' and recalled that id on the ajax page. It works good now but if I want to go back with browser button, the url moves to the previous page but the results on the page stays te same. How can I resolve that?
My new index.php JS code
<script>
$(document).ready(function(){
var idd;
load_data();
function load_data(page)
{
$.ajax({
url:"pagina.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
if (idd === undefined) {
alert("ja");
idd = 1;
alert(idd);
history.pushState({}, '', 'http://localhost:4612/pagina/1');
}
else {
idd = $("#idd").val();
history.pushState({}, '', 'http://localhost:4612/pagina/'+idd);
}
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
and my altered pagina.php
<?PHP
$connect = mysqli_connect("hidden", "hidden", "hidden","publiek2") or die("Connection failed: " . mysqli_connect_error());
$record_per_page = 50;
$page = '';
$output = '';
if(isset($_GET["page"]))
{
$page = $_GET["page"];
echo "<input type='hidden' id='idd' value='".$_GET['page']."'>";
}
else
{
$page = 1;
$idd = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC 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["merk"].'</td>
<td>'.$row["model"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC";
$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;
?>

No Data Message Show

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

How to take value of id from generated php table and delete row with that id

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>

How to add records for dynamically generated input fields

I have a form , where on clicking Add more button new fields appear . How can I store them into php variables and then put into mysql database.
I have working knowledge of php and mysql.
My HTML and javascript code is below:
<script type="text/javascript">
function($) {
$.fn.relCopy = function(options) {
var settings = jQuery.extend({
excludeSelector: ".exclude",
emptySelector: ".empty",
copyClass: "copy",
append: '',
clearInputs: true,
limit: 0 // 0 = unlimited
}, options);
settings.limit = parseInt(settings.limit);
// loop each element
this.each(function() {
// set click action
$(this).click(function(){
var rel = $(this).attr('rel'); // rel in jquery selector format
var counter = $(rel).length;
// stop limit
if (settings.limit != 0 && counter >= settings.limit){
return false;
};
var master = $(rel+":first");
var parent = $(master).parent();
var clone = $(master).clone(true).addClass(settings.copyClass+counter).append(settings.append);
//Remove Elements with excludeSelector
if (settings.excludeSelector){
$(clone).find(settings.excludeSelector).remove();
};
//Empty Elements with emptySelector
if (settings.emptySelector){
$(clone).find(settings.emptySelector).empty();
};
// Increment Clone IDs
if ( $(clone).attr('id') ){
var newid = $(clone).attr('id') + (counter +1);
$(clone).attr('id', newid);
};
// Increment Clone Children IDs
$(clone).find('[id]').each(function(){
var newid = $(this).attr('id') + (counter +1);
$(this).attr('id', newid);
});
//Clear Inputs/Textarea
if (settings.clearInputs){
$(clone).find(':input').each(function(){
var type = $(this).attr('type');
switch(type)
{
case "button":
break;
case "reset":
break;
case "submit":
break;
case "checkbox":
$(this).attr('checked', '');
break;
default:
$(this).val("");
}
});
};
$(parent).find(rel+':last').after(clone);
return false;
}); // end click action
}); //end each loop
return this; // return to jQuery
};
})(jQuery);
</script>
<script type="text/javascript">
$(function(){
var removeLink = ' <a class="remove" href="#" onclick="$(this).parent().slideUp(function(){ $(this).remove() });
return false">remove</a>';
$('a.add').relCopy({ append: removeLink});
});
</script>
<style type="text/css">
body{ font-family:Arial, Helvetica, sans-serif; font-size:13px; }
.remove {color:#cc0000}
.input{ border: solid 1px #006699; padding:3px}
</style>
</head>
<body>
<form method="post" action="">
<table width="580" border="1" class="clone" rules="groups" align="center">
<tr>
<td width="129" height="29" align="right"><strong>Child Name :</strong></td>
<td width="435"><input name="petname[]" type="text" class="txt_box" id="petname" />
</td>
</tr>
<tr>
<td align="right" height="29"><strong>Pet Image :</strong></td>
<td><input name="petimage[]" type="file" class="txt_box" id="petimage" /></td>
</tr>
</table>
<p style=" margin-left:60px;">Add More</p>
</form>
</body>
</html>
Once the form is posted, you could get the values of the posted data using :
$_POST in an array.
Then you will need to iterate through the array to be inserted into the database.
An Example:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO tablename(FirstName, LastName, Age)
VALUES ('test', 'name',25)");
mysql_close($con);
?>

How do I save JQuery UI sortable table positions to MySQL database?

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.

Categories