need a favor. I wanted to make the internal PHP script runs automatically on page load. I have problems related to passing the value of the Date and User input from the form to the internal PHP script. I have tried both $_POST and $_GET. Should I put the script in an external script? I dont really need codes, just tell me what should I look into. Thanks!
Entry Log/Edit
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" type="text/javascript" src="js/simpledtpicker.js"></script>
</head>
<body style="text-align:center;">
<div class="wrapper">
<?php include('includes/header.php')?>
<h1 style="text-align:center;">Entry Log/Edit</h1>
<span>
<form action="#" method="GET">
<table style="width:100%;">
<tr>
<th style="text-align:left;">
Entries for:
<input type="text" name="dateOfEntry" class="dateOfEntry">
<script type="text/javascript">
$(function()
{
$('*[name=dateOfEntry]').appendDtpicker(
{
"dateOnly": true,
"dateFormat": "MM/DD/YYYY",
"autodateOnStart": true,
"closeOnSelected": true
});
});
</script>
</th>
<th style="text-align:right; padding-right: 0px;">
User:
<input type="text" name="user" value="Hrobi7198228" readonly="readonly" style="border:none; background-color:transparent"/>
</th>
<th width="5px;"><input type="submit" name="submit" value="Go"></th>
</tr>
</table>
</form>
</span>
<br>
<table class="entry" style="width: 100%;">
<thead>
<?php
include ('connServer.php');
$date = date('Y-m-d', strtotime(str_replace("-","/",$_GET['dateOfEntry'])));
$username = $_GET['user'];
$query = 'SELECT `ID`, `Date`, `Description`, `TypeOfDowntime`, `Machine#` FROM `machineissuesreport` WHERE `Date`="'.$date.'" AND `UpdatedBy` = "'.$username.'" ORDER BY `ID` DESC';
$conn = mysqli_query($connection, $query);
if ($conn)
{
echo '<tr>
<th width="5px">Edit</th>
<th width="5px">Delete</th>
<th>Date</th>
<th>Details</th>
<th width="100px" style="text-align:center;">Downtime Type</th>
<th width="20px" style="text-align:center;">Machine No.</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($conn))
{
echo '<tr>';
echo '<td style="text-align: center" width="5px">Edit</td>';
echo '<td style="text-align: center" width="5px">Delete</td>';
echo '<td style="display: none;"><input type="hidden" value='.$row['ID'].'></td>';
echo '<td width="5px" style="text-align: center; padding: 0px 5px;">'.$row['Date'].'</td>';
echo '<td style="text-align: left; padding: 0px 0px 0px 12px;">'.$row['Description'].'</td>';
echo '<td style="text-align: center;">'.$row['TypeOfDowntime'].'</td>';
echo '<td style="text-align: center;">'.$row['Machine#'].'</td>';
echo '</tr>';
}
}
?>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax
({
type: 'POST',
data: {'run':run},
success: function(data)
{
}
});
$('.delete').click(function()
{
if(confirm("Are you sure you want to delete this row?"))
{
var del_id = $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type: 'POST',
url: 'machineEntryLogEdit.php',
data: {'del_id' : del_id},
success: function(data)
{
$ele.fadeOut().remove();
},
error: function (xhr, status, error)
{
alert(this);
}
});
}
});
});
</script>
</tbody>
</table>
</div>
</body>
</html>
I am still progressing on it, but please help me find the correct terms to Google. I am fairly new to PHP and AJAX.
You can write below code in a js file and include the js file in your page.
$(document).ready(function(){
$.ajax({ url: "file.php",
data: data1,
success: function(){
// Do whatever you want to do here.
}});
});
Related
I'm currently using Codeigniter and using Ajax to post my search result through the server and result the result and display on my responsive datatable. However the result was not added into my datatable and i even try to add it with .append but it just added below my table and the search function on datatable is not searching it and it still show "No data available in table".
Here are my View :
<div id="reporting" class="container">
<h3 class="section-title">Export Time Location Panel</h3>
<form id = "search">
<div class="form-group">
<div class="form-group">
<h5>Date/ Time</h5>
<input type="datetime-local" name="datetime" id = "datetime">
<?php echo form_error('datetime'); ?>
</div>
</div>
<button type="submit" class="btn btn-primary">Confirm</button>
</form><br/>
<table class="table table-bordered table-light" >
<thead>
<tr>
<td class="id">ID</td>
<td class="na">NA Name</td>
<td class="centre">Centre Name</td>
<td class="login">Date & Time</td>
<td class="lat">Latitude</td>
<td class="long">Longtitude</td>
<td class="accuracy">Accuracy</td>
<td class="place">Location Name</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<?php include('footer.php'); ?>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
var tbl = $('.table').DataTable({
responsive: true,
"order": [[0, "desc"]]
})
$( "#search" ).submit(function(event) {
event.preventDefault();
var value = $("#datetime").val();
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>location/search_record',
data:{'datetime':value},
success:function(data){
$('.table').append(data);
}
});
});
} );
</script>
Here are my Model :
public function search_record(){ //Display Record at View Page
$this->load->model('location_model');
$this->load->library('form_validation');
echo '
<tr>
<td class="id">ID</td>
<td class="na">NA Name</td>
<td class="centre">Centre Name</td>
<td class="login">Date & Time</td>
<td class="lat">Latitude</td>
<td class="long">Longtitude</td>
<td class="accuracy">Accuracy</td>
<td class="place">Location Name</td>
</tr>
';
}
You have to add data to table body by
success:function(data){ tbl.rows.add($(data)).draw(); }
Please check this link
https://jsfiddle.net/kuLcqwav/3/
https://datatables.net/examples/api/add_row.html
So im kinda trying to delete row from my mysql database using checkboxes. Here is my code. Would be glad if someone could write me down simple delete code. Tryed many but failed, stuck for hours with this :(
<html>
<head>
<title>Admin, User</title>
</head>
<body>
<?php include 'connect.php';?>
<?php include 'functions.php';?>
<?php include 'title_bar.php';?>
<h3>Sukurti Nauja uzduoti: </h3>
<form method='post'>
<?php
if(isset($_POST['submit2']))
{
$pav = $_POST['pav'];
$uzduotis = $_POST['uzduotis'];
if(empty($pav) or empty($uzduotis)){
echo "<p>Privalomi visi langai!</p>";
}
else {
$sql = ("INSERT INTO uzduotys VALUES ('','$pav','$uzduotis')");
}
if($database->query($sql) == TRUE)
{
header('location:kurtisalinti.php');
}
else {
echo "<p>Klaida!</p>";
}
}
?>
<p>Uzduoties pavadinimas:
<p><input type='text' name='pav' />
<p>Uzduotis:
<p><textarea name='uzduotis'></textarea>
<p><input type='submit' name='submit2' value='Sukurti Uzduoti' />
</form>
</p></p></p></p>
</form>
<h3>Pasalinti pasirinkta uzduoti is uzduociu saraso: </h3>
<?php
$query = mysqli_query($database,"SELECT uzid,pav,uzduotis FROM uzduotys");
$count=mysqli_num_rows($query);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Pavadinimas</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Aprasymas</strong></td>
</tr>
<?php
while($rows = mysqli_fetch_array($query)){
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" value="<?php echo $row['uzid']; ?>"></td>
<td bgcolor="#FFFFFF"><?php echo $rows['uzid']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['pav']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['uzduotis']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Istrinti Uzduotis"></td>
</tr>
<?php
?>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
Welcome to StackOverflow! Generally as a rule of thumb asking to write you some code doesn't get you very far, however I know that some people learn better from seeing it implemented and being able to modify off of that.
There is a number of ways you can do this. Using something like jquery and ajax you can post your requests without having to reload the page. Keep in mind what I have below may not fully work for you since taking the time to do this much already without a database or connection should give you an idea of what you're looking to do. Good luck!
CAUTION: PSUEDO CODE (This may not fully work and is not intended for production) The idea is to show you an approach to achieving what you are looking for.
<?php
include('connect.php');
include('functions.php');
include('title_bar.php');
if(isset($_POST['submit-uzduotis']))
{
$pav = $_POST['pav'];
$uzduotis = $_POST['uzduotis'];
if(empty($pav) or empty($uzduotis))
{
$result = "<span>Privalomi visi langai!</span>";
}
else
{
$sql = ("INSERT INTO uzduotys VALUES ('','$pav','$uzduotis')");
}
if($database->query($sql) == true)
{
header('location:kurtisalinti.php');
}
else
{
$result = "<span>Įvyko klaida!</span>";
}
}
if(isset($_POST['remove']))
{
$id = mysql_real_escape_string($_POST['remove']);
mysqli_query($database, "DELETE FROM uzduotys WHERE uzid = $id");
}
function showTableData()
{
$query = mysqli_query($database, "SELECT uzid, pav, uzduotis FROM uzduotys");
$count = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query))
{
echo '<tr id="'. $row['uzid'] .'">
<td>
<input type="checkbox" name="checkbox[]" value="'. $row['uzid'] .'">
</td>
<td>'. $row['uzid'] .'</td>
<td>'. $row['pav'] .'</td>
<td>'. $row['uzduotis'] .'</td>
<td>
<button id="remove-single" data-id="'. $row['uzid'] .'">REMOVE</button>
</td>
</tr>';
}
}
?>
<html>
<head>
<title>Admin, User</title>
<style>
.uzduotis-table {
background-color: #ccc;
border-collapse: collapse;
}
.uzduotis-table thead > td {
background-color: #333;
font-weight: bold;
}
.uzduotis-table td {
padding: 3px;
text-align: center;
background-color: #fff;
}
label {
display:block;
position:relative;
font-weight: bold;
}
</style>
</head>
<body>
<h3>Sukurti Nauja uzduoti: </h3>
<form method='post'>
<?php echo $result; ?>
<div>
<label>Uzduoties pavadinimas:</label>
<input type='text' name='pav' />
</div>
<div>
<label>Uzduoties:</label>
<textarea name='uzduotis'></textarea>
</div>
<div>
<input type='submit' name='submit-uzduoties' value='Sukurti Uzduoti' />
</div>
</form>
<h3>Pasalinti pasirinkta uzduoti is uzduociu saraso: </h3>
<table class="uzduotis-table">
<thead>
<tr>
<td>#</td>
<td>Id</td>
<td>Pavadinimas</td>
<td>Aprasymas</td>
</tr>
</thead>
<tbody>
<?php showTableData(); ?>
<tr>
<td colspan="5">
<button id="remove-selected" data-id="'. $row['uzid'] .'">REMOVE SELECTED</button>
</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
// Remove Single (Button)
$('body').on('click', '#remove-single', function() {
remove($(this).data('id'));
});
// Remove All Checked
$('body').on('click', '#remove-selected', function() {
$('.uzduotis-table tr').filter(':has(:checkbox:checked)').each(function() {
remove(this.id);
});
});
function remove(id)
{
console.log("Remove: " + id);
alert('Removing: ' + id);
$.ajax({
type: "POST",
url: '<?php echo $url; ?>',
data: { remove: id },
success: function (data) {
$('#' + id).remove();
}
});
}
})
</script>
</body>
</html>
I cleaned up a bit of the html and styles, just made it easier for me to read. Also I would recommend looking into a library such as PDO to handle your database queries as there currently isn't much in place to protect or safe guard against sql injection.
I am having problems trying to fetch some data from my database to display it in a value, I'm using Smarty as a template engine, I have my working code which is:
<div style="width: 50%">
<table id="listado" width="100%" cellpadding="2" cellspacing="1" border="0">
<thead>
<tr>
<th> </th>
<th style="text-align: center;">ID</th>
<th style="text-align: center;">NOMBRE</th>
<th style="text-align: center;">DOCUMENTO</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
{literal}
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
"url": API_PATH+"/empresas/",
"method": "GET",
"dataType": 'json',
'cache':false
}).done(function (response) {
var allregs = [];
$.each(response, function(key,val){
var items = [];
items.push('<tr>');
items.push('<td style="text-align: center;">seleccionar</td>');
items.push('<td style="text-align: center;">'+val.id+'</td>');
items.push('<td style="text-align: center;">'+val.nombre+'</td>');
items.push('<td style="text-align: center;">'+val.documento+'</td>');
items.push('</tr>');
allregs.push(items);
});
$('#listado tbody').append(allregs.join(''));
}).fail(function(jqXHR, textStatus){
if(jqXHR.status == 404){
alert("No existen registros");
}
});
$('body').on('click','.selectEmpresa',function(){
var empresaid = $(this).attr('data-id');
$.ajax({
"url": API_PATH+"/empresas/select/"+empresaid,
"method": "GET",
"dataType": 'json',
'cache':false
}).done(function (response) {
location.href = SERVER_PATH+'/';
}).fail(function(jqXHR, textStatus){
alert('error');
});
});
});
</script>
{/literal}
it works perfectly using normal thead, tbody, tr, td, what im trying to do is fetch the same data just val.nombre but inside :
<div class="container">
<section>
<select class="cs-select cs-skin-border">
<option value="" disabled selected>Seleccionar Empresa</option>
<option value="prueba1">Prueba 1</option>
<option value="prueba2">Prueba 2</option>
<option value="prueba3">Prueba 3</option>
</select>
</section>
</div>
<script src="{$smarty.const.ASSETS_FOLDER}/select-empresas/classie.js"></script>
<script src="{$smarty.const.ASSETS_FOLDER}/select-empresas/selectFx.js"></script>
<script>
(function() {
[].slice.call( document.querySelectorAll( 'select.cs-select' ) ).forEach( function(el) {
new SelectFx(el);
} );
})();
</script>
instead of setting the values manually I want to fetch it from the database dynamically
i have a script which works for deletion confirmation...
$('document').ready(function(){
$('.ask').jConfirmAction();
});
and the table of products listing is under below
<?php if(isset($query)){ ?>
<input disabled type="hidden" id="recNum" value="<?php echo $rec ?>"/>
<table id="rounded-corner" summary="2007 Major IT Companies' Profit" width="100%">
<thead>
<tr>
<th scope="col" class="rounded-company"></th>
<th scope="col" class="rounded">Product ID</th>
<th scope="col" class="rounded">Product Name</th>
<th scope="col" class="rounded">Product slug</th>
<th scope="col" class="rounded">Type</th>
<th scope="col" class="rounded">Product Category</th>
<th scope="col" class="rounded">Edit</th>
<th scope="col" class="rounded-q4">Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="7" class="rounded-foot-left"><em>All The Pages That Being Included</em></td>
<td class="rounded-foot-right"> </td>
</tr>
</tfoot>
<tbody>
<?php
foreach($query as $key => $row) {
?>
<tr>
<td><input type="checkbox" name="" /></td>
<td><?php echo $row['product_id'];?></td>
<td><?php echo $row['product_name'];?></td>
<td><?php echo $row['product_slug'];?></td>
<td><?php echo $row['type'];?></td>
<td><img src="<?php echo base_url().$row['product_image'];?>" width="80px" height="80px"/></td>
<td><img src="<?php echo base_url();?>assets/admin_assets/images/user_edit.png" alt="" title="" border="0" /></td>
<td><img src="<?php echo base_url();?>assets/admin_assets/images/trash.png" alt="" title="" border="0" /></td>
</tr>
<?php
}?>
</tbody>
</table>
<span class="bt_green_lft"></span><strong>Add new item</strong><span class="bt_green_r"></span>
<span class="bt_blue_lft"></span><strong>View all items from category</strong><span class="bt_blue_r"></span>
<span class="bt_red_lft"></span><strong>Delete items</strong><span class="bt_red_r"></span>
heres the jquery for the jQuery confirmation:
/*
* jQuery Plugin : jConfirmAction
*
* by Hidayat Sagita
* http://www.webstuffshare.com
* Licensed Under GPL version 2 license.
*
*/
(function($){
jQuery.fn.jConfirmAction = function (options) {
// Some jConfirmAction options (limited to customize language) :
// question : a text for your question.
// yesAnswer : a text for Yes answer.
// cancelAnswer : a text for Cancel/No answer.
var theOptions = jQuery.extend ({
question: "Are You Sure ?",
yesAnswer: "Yes",
cancelAnswer: "Cancel"
}, options);
return this.each (function () {
$(this).bind('click', function(e) {
e.preventDefault();
thisHref = $(this).attr('href');
if($(this).next('.question').length <= 0)
$(this).after('<div class="question">'+theOptions.question+'<br/> <span class="yes">'+theOptions.yesAnswer+'</span><span class="cancel">'+theOptions.cancelAnswer+'</span></div>');
$(this).next('.question').animate({opacity: 1}, 300);
$('.yes').bind('click', function(){
window.location = thisHref;
});
$('.cancel').bind('click', function(){
$(this).parents('.question').fadeOut(300, function() {
$(this).remove();
});
});
});
});
}
})(jQuery);
all the thing was working well,
then i made ana jax pagination for the lists;
now the problem is that after this task, the jquery confirmation isnt working, i want the jquery script to be converted into simple jquery function like this
function ask()
{
}
EDIT:
i have written the function
function ask(obj)
{
alert('hii');
//var theOptions = jQuery.extend ({
var question= "Are You Sure ?";
var yesAnswer= "Yes";
var cancelAnswer= "Cancel";
//e.preventDefault();
var thisHref = $(obj).attr('href');
alert(thisHref) ;
if($(obj).next('.question').length <= 0)
$(obj).after('<div class="question">'+question+'<br/> <span class="yes">'+yesAnswer+'</span><span class="cancel">'+cancelAnswer+'</span></div>');
$(obj).next('.question').animate({opacity: 1}, 300);
$('.yes').bind('click', function(){
window.location = thisHref;
});
$('.cancel').bind('click', function(){
$(obj).parents('.question').fadeOut(300, function() {
$(obj).remove();
});
});
}
and i am calling this from
<img src="<?php echo base_url();?>assets/admin_assets/images/trash.png" alt="" title="" border="0" />
its taking the effect also;
but just after the animating effect, its getting redirected to the link, i need to make it stay, so that user can choose the option. but i cant...
MORE EDIT:
Ok i got the answer; i used the small code return false and it solved my problem
but then there's another problem
this line of code isnt working
$('.cancel').bind('click', function(){
$(obj).parents('.question').fadeOut(300, function() {
$(obj).remove();
});
});
You need to bind $('.ask').jConfirmAction(); to all the links again after you have gone to the new page.
I added Edit button to my jQuery Datatable. When the user clicks on this button, the row becomes editable. Updated row should be saved to MySQL DB, but here comes the problem - the updated row is not saved to DB. Firebug does not show any error message. Can someone help me figure out the problem?
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#newspaper-b').dataTable({
"sPaginationType":"full_numbers",
"aaSorting":[[3, "asc"]],
"bJQueryUI":true
});
$(".edit_but").click(function() {
var ID=$(this).attr('id');
$("#first_"+ID).hide();
$("#last_"+ID).hide();
$("#first_input_"+ID).show();
$("#last_input_"+ID).show();
});
$(".edit_tr").change(function() {
var ID=$(this).attr('id');
var first=$("#first_input_"+ID).val();
var last=$("#last_input_"+ID).val();
var dataString = 'flightNum='+ ID +'&from='+first+'&STADate='+last;
$("#first_"+ID).html('<img src="load.gif" />'); // Loading image
if(first.length>0&& last.length>0) {
$.ajax({
type: "POST",
url: "callpage.php?page=tables/edit.php",
data: dataString,
cache: false,
success: function(html) {
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
} else
{
alert('All fields must be filled out.');
}
});
// Edit input box click action
$(".editbox").mouseup(function() {
return false
});
// Outside click action
$(document).mouseup(function() {
$(".editbox").hide();
$(".text").show();
});
$("tr").click(function(){
$(this).addClass("selected").siblings().removeClass("selected");
});
});
</script>
<table id="newspaper-b" border="0" cellspacing="2" cellpadding="2" width = "100%">
<thead>
<tr>
<th scope="col">Flt Num</th>
<th scope="col">From</th>
<th scope="col">STA Date</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach ($result1 as $row):
$flightNum=$row['flightNum'];
$from=$row['frm'];
$STADate=$row['STADate'];
?>
<tr id="<?php echo $flightNum; ?>" class="edit_tr">
<td><?php echo $row['flightNum'];?></td>
<td class="edit_td">
<span id="first_<?php echo $flightNum; ?>" class="text">
<?php echo $from;?>
</span>
<input type="text" value="<?php echo $from;?>"
class="editbox" id="first_input_<?php echo $flightNum; ?>"/>
</td>
<td class="edit_td">
<span id="last_<?php echo $flightNum; ?>" class="text">
<?php echo $STADate; ?>
</span>
<input type="text" value="<?php echo $STADate; ?>"
class="editbox" id="last_input_<?php echo $flightNum; ?>"/>
</td>
<td class="edit_td"><?php echo $row['pkID']; ?></td>
<td id="<?php echo $flightNum; ?>" class="edit_but">
<div>
<img src='images/edit.png' alt='Edit' />
</div>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
edit.php
<?php
include_once 'include/DatabaseConnector.php';
if(isset($_POST['flightNum'])) {
$flightnum=$_POST['flightNum'];
$from=$_POST['from'];
$STADate=$_POST['STADate'];
$query = 'UPDATE flightschedule
SET frm="'.$from.'",STADate="'.$STADate.'"
WHERE flightNum="'.$flightNum.'"';
DatabaseConnector::ExecuteQuery($query);
echo '1';
} else {
echo '0';
}
?>
Try $(".edit_tr input").change() as the trigger.
Change events are limited to inputs, selects and textareas only, but you've tried binding it to a table row. The code above will bind it to any inputs inside the row with the class.