I know that this question might have been asked before, but I can't figure it out.
AJAX is passing the selected date to PHP and it should dynamically update this $select with the data from AJAX and update the query made to teh database. But $_POST['date'] seems to be empty and nothing is happening.
AJAX
$(window).ready(function(event) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){ dd='0'+dd; }
if(mm<10){ mm='0'+mm; }
var today = yyyy+'-'+mm+'-'+dd; // document.getElementById("DATE").value = today;
selectedDate = today; // selectedDate = '2016-04-17';
var options = {
selectedDate: selectedDate,
onSelectedDateChanged: function(event, date) {
var d = new Date(date);
passDate(d);
}
};
passDate(new Date(selectedDate));
$('#paginator').datepaginator(options);});
function passDate(d) {
date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
console.log(date);
$.ajax({
data: date,
type: "POST",
url: "php/table_body.php"
});};
PHP
<?php
$select = $_POST['data'];
$sql_query="SELECT * FROM users where date = '$select'";
// $sql_query="SELECT * FROM users WHERE date = '2017-05-12'";
$result_set=mysql_query($sql_query);
if(mysql_num_rows($result_set)>0)
{
while($row=mysql_fetch_row($result_set))
{
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
<td><?php echo $row[3]; ?></td>
<td><?php echo $row[4]; ?></td>
<td><?php echo $row[5]; ?></td>
<td><?php echo $row[6]; ?></td>
<td><?php echo $row[7]; ?></td>
<td align="center"><span class="glyphicon glyphicon-edit"> Edit</td>
<td align="center"><span class="glyphicon glyphicon-trash"> Delete</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="5">No Data Found !</td>
</tr>
<?php
}
Can you help figure how to fix it. Thank you
In the ajax javascript:
data: { date: date },
You didn't define the variable key for the date.
Also change in the php
$select = $_POST['date'];
And as suggested in the comments code for SQL injection protection.
check your parameter on $.ajax for the data, it should be like
$.ajax({
url: "php/table_body.php",
method: "POST",
data: { date: date}
});
for more information visit this link for ajax ref http://api.jquery.com/jquery.ajax/
Related
Apologies if this question has been asked previously.
I am currently generating a basic table using PHP and have one cell where a user can add a comment.
When the user types a comment into the editable cell it saves it to the database table "TechComment column".
I want the editable cell to "disable editing" after the user entered the comment.
My code below:
Table Code
require_once "../linkd.php";
$sql = "select * from DispatchTech where Technician = ? and convert(date, Inserted) = convert(date,
getdate()) order by Completed ASC, DoneWhen";
$ses = $_SESSION['Username'];
$par = array($ses);
$stmt = sqlsrv_query($conn, $sql, $par);
if($stmt){
$count = 1;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$id = $row['Id'];
$txt = $row['TechComment'];
?>
<tr>
<?PHP
if($row['Completed'] == NULL){
print "<td><button onclick=location.href='complete.php?Id=".$row['Id']."'>Complete</button></td>";
}
elseif($row['Completed'] != NULL){
print '<td><span align="center" style="font-size:15px;">✅</span></td>';
}
if($row['Area'] == NULL){
print "<td><button onclick=location.href='arrive.php?Id=".$row['Id']."'>On Site</button></td>";
}else{
print "<td>";
print date_format(new DateTime($row['Area']), "H:i:s");
print "</td>";
}
?>
<td><?php echo $row['TermID']; ?></td>
<td><?php echo $row['Location']; ?></td>
<td><?php echo $row['DMRef']; ?></td>
<td><?php echo $row['Error']; ?></td>
<td><?php echo $row['Description']; ?></td>
<td><?php echo date_format($row['Inserted'], "H:i:s") ?></td>
<td><div contentEditable='true' class="edit" id='TechComment_<?php echo $id; ?>'><?php echo $txt; ?>
</div> </td>
<td><?php echo $row['Timeframe']; ?></td>
</tr>
<?PHP
$count ++;
}
}
?>
Jquery/Ajax Code:
$(document).ready(function(){
$('.edit').click(function(){
$(this).addClass('editMode');
});
$(".edit").focusout(function(){
$(this).removeClass("editMode");
var id = this.id;
var split_id = id.split("_");
var field_TechComment = split_id[0];
var edit_id = split_id[1];
var value = $(this).text();
$.ajax({
url: 'update.php',
type: 'post',
data: { field:field_TechComment, value:value, id:edit_id },
success:function(response){
console.log('Save successfully');
}
});
});
});
I found this short jquery script that will do the trick but can't get it to work.
$('.edit').editable(function (value, settings) {
return value;
});
Might it be because i'm using ajax?
I am not that familiar with ajax.
Any help will be greatly appreciated.
You can achieve it by setting contentEditable to false in your ajax response, like:
$(".edit").focusout(function(){
$(this).removeClass("editMode");
var id = this.id;
var split_id = id.split("_");
var field_TechComment = split_id[0];
var edit_id = split_id[1];
var value = $(this).text();
$.ajax({
url: 'update.php',
type: 'post',
data: { field:field_TechComment, value:value, id:edit_id },
success:function(response){
console.log('Save successfully');
$('#'+id).prop('contenteditable', false );
}
});
});
I want to add a delete button to this table, to delete the query from Database. I have the Ajax and PHP codes here :
<?php
require_once 'dbconfig.php';
$stmt = $pdo->prepare("SELECT * FROM test");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['server']; ?></td>
<td><?php echo $row['reference']; ?></td>
<td align="center"><a id="<?php echo $row['id']; ?>" class="delete-link" href="#" title="Delete">
<img src="images/delete.png" width="20px" />
</a></td>
</tr>
<?php
}
?>
the ajax :
$(document).ready(function(){
/* Data Delete Starts Here */
$(".delete-link").click(function()
{
var id = $(this).attr("id");
var del_id = id;
var parent = $(this).parent("td").parent("tr");
if(confirm('Sure to Delete ID no = ' +del_id))
{
$.post('delete.php', {'del_id':del_id}, function(data)
{
parent.fadeOut('slow');
});
}
return false;
});
/* Data Delete Ends Here */
});
delete.php :
<?php
include_once 'dbconfig.php';
if($_POST['del_id'])
{
$id = $_POST['del_id'];
$stmt=$db_con->prepare("DELETE FROM test WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
The row selected doesn't seem to get DELETED in the DB ... i have no error too.
You had pass data incorrectly . Please try this
$(document).ready(function()
{
$('table#delTable td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "view.php",
data: {id:id},
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
});
I want to delete row in database without reloading the page. I have written following codes. It does delete row in page but not in database. which means connection not going to ajax. pls help.
<?php
$advances_result= mysqli_query($conn, "SELECT * FROM advances") or die("error");
?>
<table border>
<caption>ADVANCES</caption>
<tr>
<th>Date</th>
<th>EmpName</th>
<th>EmpCode</th>
<th>Amount</th>
<th>Comment</th>
<th>Action</th>
</tr>
<?php
while($row = mysqli_fetch_array($advances_result)){
?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['empname'];?></td>
<td><?php echo $row['empcode'];?></td>
<td style='text-align:right'><?php echo $row['amount'];?></td>
<td><?php echo $row['comment'];?></td>
<td><button class="delete" id="<?php echo $row['id']; ?>" > Delete</button></td>
</tr>
<?php
}
?>
</table>
'jquery part'
<script>
$(document).ready(function(){
$(".delete").click(function() {
if (confirm("Do you want to delete this row?"))
{
var row = $(this).parents('tr');
var id = row.attr("id");
var data = 'id=' + id ;
$.post({
type: "post",
url: "deleteadvances.php",
data: data,
cache: false,
success: function(){
row.slideUp('slow', function() {$(row).remove();});
}
});
}
return false;
});
});
</script>
'deleteadvances.php' page:
<?php
include("connection.php");
$id = $_POST['id'];
mysqli_query($conn,"INSERT INTO advancehistory SELECT * FROM advances WHERE ID='".$id."'");
mysqli_query($conn,"DELETE FROM advances WHERE ID='".$id."'");
?>
You need to test the output of mysqli_query in deleteadvances.php, if all good, it shows JSON Ok message that is easy parsable with $.post on the jQuery side.
e.g: {"deleted":"id"} on success or {"error":404} on error not found.
I think the id that you're passing from javascript to ajax is incorrect.
var data = 'id=' + id;
is appending the id with string 'id=' and now it finally becomes a string. When it is being passed to ajax, there is just a value and not a [key, value] pair. So, when you are accessing it in php you will get wrong id or Null value.
Try:
$.post({
type: "post",
url: "deleteadvances.php",
datatype : 'json',
data: {
id : id
},
cache: false,
contentType : 'application/x-www-form-urlencoded; charset=utf-8'
});
Change 'deleteadvances.php' page:
<?php
include ('connection.php');
$id=$_POST['id'];
$delete = "DELETE FROM table_name WHERE id=$id";
$result = mysqli_query($db,$delete) or die("Bad SQL: $delete");
?>
I'm having a problem in updating the qty field in my database using ajax. I don't know where the error occur because when I tried to click the minus button it keeps on subtracting it multiple times. I've google same problem but didn't find any solution. Here is my code.
Here is my CONTROLLER:
public function deduct(){
$this->inpatient_model->deduct();
$data['inpatient'] = $this->inpatient_model->getinpatientlab();
$this->load->view('admin/queryinpatient',$data);
}
Here is my MODEL:
public function deduct(){
$this->db->select('*');
$this->db->from('inpatientlab');
$this->db->where('ilid',$this->input->post('lid'));
$query = $this->db->get();
$row = $query->result_array();
if($query->num_rows() > 0 ){
if($row[0]['qty'] > 1){
$uno = 1;
$this->db->set('qty','qty-'.$uno,FALSE)
->where('ilid',$this->input->post('lid'))
->update('inpatientlab');
}
}
}
Here is my VIEW:
<?php if($inpatient): ?>
<table class="table table-striped">
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
<th>Sub Total</th>
<th>Action</th>
</tr>
<?php foreach($inpatient as $rows): ?>
<tr>
<td><?php echo $rows->ldesc; ?></td>
<td><?php echo $rows->qty; ?></td>
<td><?php echo $rows->lprice; ?></td>
<td><?php echo number_format($rows->qty * $rows->lprice,2); ?></td>
<td>
<button value="<?php echo $rows->ilid; ?>" class="btn btn-danger btnRemove"><i class="icon-trash"></i></button>
<button value="<?php echo $rows->ilid; ?>" class="btn btn-danger btnMinus"><i class="icon-minus"></i></button>
</td>
</tr>
<?php endforeach; ?>
</table>
<script type="text/javascript" >
(function(){
$(document).on('click','.btnMinus',function(){
var lid = $(this).val(),
pid = $('.pid').val(),
dataString = "id=" + pid + "&lid=" + lid;
console.log(dataString);
$.ajax({
type:"POST",
url: base_url + "inpatient/deduct",
data:dataString,
success:function(data){
$('.pickedlab').html(data);
}
})
return false;
});
})()
My View in here is also loaded via ajax inside a bootstrap-modal. I really have no idea why it keeps on subtracting multiple times. Any help?
Have you tried using the browser debug and find out whether your AJAX is calling multiple times. I am not familiar with your Controller-Model settings, normally my models are pure POCO class only. All computations are done at the controller level.
I am trying to make a "td" disappear whenever the date occured before that date today (in the past). But what is happening is that only the first column is affected while the others aren't.
<script type="text/javascript">
//<![CDATA[
function vanish() {
downloadUrl("bckendcommmap.php", function(data) {
var xml = data.responseXML;
var markers50 = xml.documentElement.getElementsByTagName("marker50");
// Split timestamp into [ Y, M, D, h, m, s ]
for (var i = 0; i < markers50.length; i++) {
var newdate = markers50[0].getAttribute("date");
var trainid = markers50[0].getAttribute("trainingid");
var t = newdate.split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2]);
alert(d);
var rightNow = new Date();
var trainingDate = new Date(d);
if (rightNow < d ) {
document.getElementById("assess").innerHTML = ""; /* make it disappear */
}
else if (rightNow > d ) {
document.getElementById("edit").innerHTML = "";
}
// -> Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
Here are parts of the table and the td:
<body onload="vanish();">
<table id="gradient-style" width="290" border="0" cellspacing="0" cellpadding="0" >
<thead>
<tr>
<td align="center"><strong> Training Name</strong></td>
<td align="center"><strong> Description</strong></td>
<td align="center"><strong> Location</strong></td>
<td align="center"><strong> Date</strong></td>
<td align="center"><strong> Time Start</strong></td>
<td align="center"><strong> Time End</strong></td>
<td align="center"><strong> Capacity</strong></td>
<td align="center" colspan="2"><strong>Actions</strong></td>
</tr>
</thead>
<?php
while($rows=mysql_fetch_array($get)){
?>
<tbody>
<tr>
<td><?php echo $rows['title']; ?></td>
<td><?php echo $rows['description']; ?></td>
<td><?php echo $rows['location']; ?></td>
<td><?php echo $rows['date']; ?></td>
<td><?php echo $rows['start']; ?></td>
<td><?php echo $rows['end']; ?></td>
<td><?php echo $rows['capacity']; ?></td>
**<td align="center"><div id="edit">Edit</div></td><td align="center"><div id="assess">Assess Training</div></td>**
</tr>
</tbody>
<?php
}
?>
</table>
</body>
This line is the td that I'm trying to vanish with respect to the date:
<td align="center"><div id="edit">Edit</div></td><td align="center"><div id="assess">Assess Training</div></td>
You are only hiding the div, if you want to hide td Try this:
**<td id="edit" align="center"><div>Edit</div></td><td id="assess" align="center"><div>Assess Training</div></td>**
And the html code is inside a while loop so you will have multiple div's with same id! You need to give them unique ids:
$i = 0;
while($rows=mysql_fetch_array($get)){
/* Code... */
<?php
$i = $i + 1;
}
?>
And
<div id="assess<?php echo $i ?>>
And in your javascript:
/* Code... */
if (rightNow < d ) {
var i = 0;
while(document.getElementById("assess" + i) != null) {
document.getElementById("assess").innerHTML = ""; /* make it disappear */
i++;
}
/* Code.../
It's a bit hard to tell what the resulting full HTML in the page looks like, but do you realize that you can only have one object in a web page with a given ID. So, you can't have multiple objects with id="assess". If that is what you're doing, then getElementById will likely only return the first one - though the exact behavior is undefined because it's not valid HTML.
Second, why not just use CSS to hide things rather than clearing the innerHTML. For example, you could use a class="assess" instead of the id="assess". And, then create a CSS rule like this:
.triggerHide .assess {display: none;}
Then, when you want to hide that all assess classes in the table, you simple add the class "triggerHide" to the table. Boom, all the objects with the class assess in the table will all hide.