How to update data directly in row? - php

I have a problem with my code. I have a php script where i, in a while, i write a table in html with html name and html value attr with the data of database, like the printscreen above
My table was assembled with input inside the TDs, to be able to "edit" directly in the table, without MODAL or redirection
</thead>
<tbody id="corpoTabela">
<?php
$i = 1;
while ($row = mysqli_fetch_array($result)) :;
?>
<tr>
<form name="presencaForm" id="presencaForm" method="POST">
<input type="hidden" id="idcrmmedico" name="idcrmmedico" value="<?php echo $row['id']; ?>"></input>
See that the opening of the form tag is inside the while, that is, for each row of the table, for each TR, I have a form (all with the same name)
The end of the form tag still inside php while. The Button, who receives the ID referring to the record in the DB, has the same name of the form
<td><button id="d" name="presencaForm" value="<?php echo $row['id'] ?>" class="btn btn-sm btn-info">Atualizar</a></td>
<td>
<button type="submit" id="" name="deletamedico" class="btn btn-sm btn-danger">Excluir</button>
</td>
</form>
</tr>
<?php
endwhile;
}
?>
</tbody>
This is my ajax script, which updates the data in the database without refreshing the page and returning me a success message.
<script>
$(document).ready(function() {
$('#presencaForm').on('submit', function(event) {
event.preventDefault();
$("#alert").css('display', 'none');
console.log("Botão Clicado!");
$.ajax({
url: "DAO/medico/update.php",
method: "POST",
data: $(this).serialize(),
dataType: "json",
success: function(data) {
if (data[0] == true) {
$("#success").html('Médico ' + data[1] + ' atualizado com sucesso');
$("#success").show();
setTimeout(function() {
$("#success").hide();
}, 5000);
}
}
})
});
});
</script>
The problem is that if i try to refresh the second line, the page just refreshes.
I used the code below to check, and I saw that all buttons return only the first record in the LOG.
Is there any way to update the data as I want, right in the table?
$(document).ready(function() {
$("button[name='presencaForm']").on("click", function(event) {
event.preventDefault();
for (var i = 1; i < document.getElementById("dataTable").rows.length; i++) {
console.log($('#idcrmmedico').val());
}
var val = document.getElementById('d').value;
var x = document.getElementById("dataTable").rows.length;
});

id is unique,if you want to control a group of form,you can use class.
For example:
<form class="presencaForm" method="POST">
Then in your javascript:
$('.presencaForm').on('submit', function(event) {

Related

How to use a value imported from a database

Hey Everyone here is my question .
The code below gets data from my database and displays it both in an input field and a button. I want it to be in such a way that if i click the button it should get the value(which is imported from the db).But the problem i am facing is that all the inputs and buttons have the same ids so it only captures the value of the first button(or so i think). How can i make it in such a way that for every button i click it should have its own separate value.
<?php
$dbcon=mysqli_connect("localhost","root","");
mysqli_select_db($dbcon,"codex");
require('config/server.php');
?>
<table class="table table-striped">
<th>ID</th>
<?php
$view_users_query="select * from users";//select query for viewing
users.
$run=mysqli_query($dbcon,$view_users_query);//here run the sql
query.
while($row=mysqli_fetch_array($run))//while look to fetch the result
and store in a array $row.
{
?>
<!--here showing results in the table -->
<form id="loginForm" method="" action="" novalidate>
<tr>
<div class="panel2">
<main class="content">
<td><input name="hanis" id="hanis" type="text" value="<?php echo
$row['email']?>" autofocus /></td>
<td><button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata()" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button><</td>
</main></div>
</div>
</div>
</form>
<?php } ?>
</tr>
<script type="text/javascript">
function hanisdata() {
var hanis=$("hanis").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
NOTE :- Don't use same id for elements
You can get values by passing this with onclick function like onclick="hanisdata(this)"
Example
<button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata(this)" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button>
Then you can get specific element in js and then can find parent and search for input field in that like below example.
JS CODE
<script type="text/javascript">
function hanisdata(el) {
var hanis=$(el).parent().find("input").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>

Php echo button onclick get id

I hava a dynamic list, loading from database in my php page.This list also have a delete button. When i click this button i need to get id of this button and delete from database that line with php code.
$dbh = new PDO("sqlite:database.sdb");
$sql ="SELECT * FROM clip";
foreach ($dbh->query($sql) as $row)
{
print 'Id: '. $row['id'] .'<br />';
echo '<input type="submit" id="'.$row['id'].'" value="delete" name="del">';
}
also this is my final code for button click;
$dbh->exec("delete clip where id='in here should be button id'");
How can i connect with this two code. Thanks already.
Given the level of your question I am assuming you are unfamiliar with jQuery and AJAX, but you should research both.
For a simple solution not using these you could do as follows:
Change the output to be <input type="button" id="'.$row['id'].'" value="Delete" onclick="do_delete(this.id)">;
Then you need a php script on the server side to handle the delete function, e.g. yourhandler.php
<?
//connect to DB here
if ($_POST['id']) {
$sql = "delete from clip where id=:delete_id";
$stmt = $dbh->prepare($sql);
$stmt->execute([':delete_id'=>$_POST['id']]);
}
?>
Then on the client side you need a form which submits when the button is clicked. Here is an example form code:
<form action="yourhandler.php" method="post" id="myform">
<!--Your PHP script which creates buttons-->
<input type="hidden" value="" name="id" id="delete_id">
</form>
<script>
function do_delete(which) {
var x = document.getElementById('delete_id');
x.value=which;
document.getElementById('myform').submit();
}
</script>
You can use this working jquery template for your task. It binds to all inputs that has a name="del".
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$('input[name="del"]').on('click', function() {
alert('button id is '+$(this).attr('id'));
var button_id = $(this).attr('id');
$.ajax({
method: 'post',
url: "delete.php",
data: {'did':button_id},
dataType: "html",
success: function(result) {
alert(result);
}
});
});
});
</script>
In your PHP delete file, you can retrieve the delete id via $_POST['did'].

jQuery How do I call current/correct value after popup

Basically I have a list of files composed from a foreach loop that all have the same code except for the name, which carries the file_id for each file. My problem is that when I added an on-click pop-up event I lose the ability to fetch the current $(".flag") attribute name. Is there a way that I can pass it along the way so I can use it in the end?
PHP: (the user sees the link which they can click...remember there are several of these as a result from the foreach loop. I'm showing one for example)
echo "<td><a href='#' class='flag' name='$files[id]' >Click Here</a> ( $files[nums] )</td>";
jQuery: (on-click this will happen)
$(".flag").live('click', function() {
$(".pop").show("slow");
return false;
});
HTML: this div will popup
<div class="pop">
<form method="post" id="new_folder" >
<p><label for="folder">Reason for Reporting?</label><textarea id="report_reason" name="report_reason" maxlenght="100" style="resize:none" cols="30" rows="5">Please limit your response to 100 characters.</textarea></p>
<p><input type="submit" value="Submit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
</form>
</div>
jQuery: on submit I need to send the current $files['id'] and textarea value via ajax. The textarea sends the correct data, but the $(".flag") instead of being the id of the selected link it is the id of the first fetched id from the foreach loop
$("#message_submit").on("click", function(e){
var fileID = $(".flag").attr("name");
var text = $("#report_reason").val();
$(".pop").hide("slow");
$.ajax({
url: '<?php echo base_url().'home/report_file';?>',
type: 'POST',
data: { val: fileID, val2: text },
dataType: 'json',
success: function(output_string){
$(".success").text("You have flagged this file!!").show().css({"color" : "green", "margin-top" : "10px"});
$(".success").fadeOut(10000);
}
});
return false;
});
You can save the .flag link being clicked and later use it.
var flagClicked;
$(".flag").live('click', function() {
$(".pop").show("slow");
flagClicked = $(this);
return false;
});
$("#message_submit").on("click", function(e){
var fileID = flagClicked.attr("name");
....

jQuery clone table row in form does not submit cloned fields

Below is a simplified example that demonstrates the problem I am having. One hundred percent of code is posted below.
Three files work together: testa.php, testb.php, and testc.js. (FWIW, testa.php could function as the index.php, but this is just a demo)
OVERVIEW:
TESTA.PHP
When user clicks anchor tag, sends value to testb.php
Receives ajax response from testb.php into div #reportstable, within FORM structure
Form is submitted to itself, so it prints $_POST data -
TESTB.PHP
receives value from TESTA.PHP, via ajax
outputs table that corresponds to received values
(In this example, I removed how received value is used, but still retained this structure as it affects the jQuery in testc.js)
TESTC.JS
the jQuery that makes it (partially) work
PROBLEM 1: If user adds more than one "document" (i.e. row), only data for the last document appears in the POST data..
PROBLEM2: DocTitle and FileName IDs (dt1, fn1) are not POSTED as they appear in the DOM. In the DOM, their IDs are incremented properly (dt11, dt12, dt13, etc) but when POSTed only one comes through and it has not been incremented. (Use firebug to inspect table elements after adding a couple of documents.
PROBLEM3: First click doesn't "take" when clicking the "choose file" anchor when adding a new document. Any thoughts on this one?
TESTA.PHP
<?php
If (empty($_POST)===false) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
}
?>
<html><body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery-custom-file-input.js"></script>
<script type="text/javascript" src="testc.js"></script>
<br />
Project*:<br />
Click Me
<form action="" method="post">
<div id="reportstable">
</div>
</form>
</body></html>
TESTB.PHP
<?php
$project_id = $_POST['project_id'];
if ($project_id == 5) {
echo '
<table id="DocTable">
<tr>
<th width="150">Document Title</th>
<th width="150">File Name</th>
</tr>
<tr name="tr2" id="tr2" style="display:none;">
<td><input type="text" name="dt1" id="dt1"></td>
<td>
<input type="hidden" name="fn1" id="fn1">
<span id="sp1">choose file<span>
</td>
</tr>
</table>
<br />
add document<br />
<br />
<input type="submit" name="submit" id="submit_it" value="Submit">
';
}
TESTC.JS
$(function(){
var count = 1;
//*******************************************************************
$('#project_pick').click(function(e) {
$(this).hide();
$.ajax({
type: "POST",
url: "testb.php",
data: "project_id=5",
success:function(data){
$('#reportstable').html(data);
}
});
});
//*******************************************************************
$(document).on('click','#ah11',function() {
$(this).file().choose(function(e, input) {
$('#fn11').val(input.val());
$('#sp11').html(input.val());
$('#sp11').css('color','grey');
});
});
//*******************************************************************
$(document).on('click','#ah12',function() {
$(this).file().choose(function(e, input) {
$('#fn12').val(input.val());
$('#sp12').html(input.val());
$('#sp12').css('color','grey');
});
});
//*******************************************************************
$(document).on('click','#ah13',function() {
$(this).file().choose(function(e, input) {
$('#fn13').val(input.val());
$('#sp13').html(input.val());
$('#sp13').css('color','grey');
});
});
//*******************************************************************
$(document).on('click', '#add_row', function() {
$("table#DocTable tr:nth-child(2)")
.clone()
.show()
.find("a, input, span, tr").each(function() {
$(this)
.val('')
.attr('id', function(_, id) {
return id + count;
});
})
.end()
.appendTo("table");
count++;
if (count == 4) {
$('#add_row').prop('disabled', 'disabled');
}
}); //end fn add_row
//*******************************************************************
$(document).on('click', '#submit_it', function() {
alert('This will be submitted now');
});
//*******************************************************************
});
It seems in your javascript that you are changing the values of the id attribute only. However, when you post a form, the id attribute is irrelevant and not posted, you need the name attribute instead.
So where you are changing id's, you really should be changing names (and id's to if you really need them as they need to be unique).
However, a far easier solution would be to use arrays for names, like:
<input type="text" name="dt[]">
If you copy / clone elements with these names and post the form, you will get an array in your $_POST['dt'].

Jquery not considering new div that is added by Jquery + php + jquery

I have a php page where I add and delete items from database using Jquery + PHP + AJAX.
Now I am able to delete and add when that page loads for the first time.
Now if I first add an element; which in turn adds record to the DB and then updates the div that contains all the listing of divs.
Example:
<div id="all_items">
<div id= "item_1">
<a id="delete_link">...</a>
</div>
<div id= "item_2">
<a id="delete_link">...</a>
</div>
.... Upto Item n
</div>
Now I replace the div with id all_items.
Now I have jQuery at the bottom of the page which calls ajax on a tag of delete_link.
Situtation is:
When page is loaded I can delete any item from the list.
But if I page load i add new item first. (which will update all_items div) after that if I try to click on delete link. Jquery on click selector event is not fired and which in turn doesn't do delete ajax operation.
I couldn't figure out why this is happening.
Looking for some help here.
EDITED:
Sorry for not writing code earliar.
Following is the jQuery I am talking about.
<script type="text/javascript" >
var jQ = jQuery.noConflict();
jQ(function() {
jQ("#submit_store").click(function() {
var store_name = jQ("#store_name").val();
var dataString = 'store_name='+ store_name;
dataString += '&mode=insert';
if(store_name =='')
{
alert("Please Enter store Name");
}
else {
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ("#dvstoreslists").html(html);
document.getElementById('store_name').value='';
document.getElementById('store_name').focus();
}
});
}
return false;
});
jQ(".store_delete").click(function() {
var store_id = jQ(this).attr('id');
var id = store_id.split("_");
var dataString = 'store_id='+ id[2];
dataString += '&mode=delete';
var to_delete = "#store_list_" + id[2]
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ(to_delete).hide("slow");
}
});
return false;
});
});
</script>
So If on page load, I delete then delete on click jquery event is fired. But after adding new store and replacing div of stores with new div. then jQuery on click event is not fired.
My HTML is as below.
<div class="sbBox stores">
<form id="add_storefrm" name="add_storefrm" method="post" action="" >
<div class="dvAddStore">
<div class="dvName" id="store_list">
<input type="text" id="store_name" name="store_name">
<input type="hidden" value="addstore" id="mode" name="mode">
</div>
<div class="btnAddStore">
<input type="submit" name="submit_store" value="Add Store" id="submit_store">
</div>
</div>
<div id="dvstoreslists">
<?php
$query = "SELECT * FROM #__shoppingstore order by store_id desc;";
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo "<div class=dvlist id=store_list_".$row->store_id ."><div class=dvStoreListLeft>";
echo "<div class='slname'><h3>" . $row->store_name . "</h3></div>";
?>
<div class="slDelBtn">
<p id = "p_store_<?php echo $row->store_id ; ?>">
<a id="store_delete_<?php echo $row->store_id ; ?>" class="store_delete" alt="Delete" onclick="DeleteStore(<?php echo $row->store_id ; ?>);" >
</a>
</p>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
Sorry folks for not posting the code earliar.
the ID should always be unique so use class instead
in your case : <a id="delete_link">...</a> to <a class="delete_link">...</a>
When you replace the contents of #all_items any event handlers that were bound to any descendants will no longer exist. You can use event delegation, using the on method, to solve this:
$("#all_items").on("click", ".delete_link", function() {
//Do stuff
});
Notice that I'm using a class selector (.delete_link) instead of an ID selector for the links. It's invalid to have duplicate IDs in the same document.
Also note that the above will only work if you are using jQuery 1.7 or above. For older versions, use delegate instead:
$("#all_items").on(".delete_link", "click", function() {
//Do stuff
});
This works because DOM events bubble up the tree from their target. So a click on a link which is a descendant of #all_items will bubble up through all of its ancestors and can be captured when it reached #all_items.
use live() instead of .bind()
It seems you are trying to delete dynamically added delete_link so i think you should use
$('id or class').on(click,function(){});

Categories