I have this script which is triggered when a button with the class .press_me is pressed.The buttons are on a column from a php generated mysql table:
$result = mysqli_query($con,"SELECT * FROM tbname");
echo "<table id='main'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='right-middle user'>" . $row['ID'] . "</td>";
echo "<td class='right-middle user'>" . $row['Nume'] . "</td>";
echo "<td class='right-middle done'>" . $row['Teme_facute'] . "</td>";
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me'>" ."</td>";
echo "<td class='right-middle undone'>" . $row['Teme_nefacute'] . "</td>";
echo "<td class='right-middle uncheck'>" . "<img src='img/uncheck.png'>" . "</td>";
echo "<td class='side-table resetDone'>" . "<img src='img/resetDone.png'>" . "</td>";
echo "<td class='side-table resetUndone'>" . "<img src='img/resetUndone.png'>" . "</td>";
echo "</tr>";
}
echo "</table>";
And the script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
And counter.php:
<?php
echo $_POST["id"];
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
I'm having trouble updating only the value on the same row as the button pressed.When i run the page in this configuration counter.php returns no id passed and i think the problem is with the passing of the row id. Can anyone help me update only the value on the row with the pressed button?
I'm aware of sql injection but it's not the main problem now
Your id is empty
try this
echo "<td class='right-middle check'>" . "<img data-id='{$row['ID']}' src='img/check.png' class='press_me'>" ."</td>";
And in the script use this
var id=$(this).data("id");
change you javascript, looks like you are not sending data at all
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php",
// add this line
data: { id: id}
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
Replace below script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo $row[ID]; ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
NOTE: I assume that you are working with single record. If not then it
will going wrong.
If this is working wrong then replace .press_me line with below:
$id = $row['ID'];
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me' id='<?php print($id);?>' >" ."</td>";
And script is like:
var id = $(this).attr("id");
Hope this help you well!
Related
I want to create a table with editable contents(using an "edit" button on each row), without the use of Bootstrap, or any other plugin.
I want to only use HTML,PHP,AJAX,JavaScript. Is this kind of task possible, and if so, can someone post some sample code or example?
SQL results work fine.
$sql_query = "SELECT User.user_id,User.name,User.surname,User.username,User.password,Role.role_name FROM User INNER JOIN Role ON User.role_id = Role.role_id";
$result = mysqli_query($conn, $sql_query);
$role_name = 'role_name';
while($rows = mysqli_fetch_array($result))
{ echo "<tr>";
echo "<td> $rows[$user_id]</td>";
echo "<td> $rows[$name]</td>";
echo "<td> $rows[$surname]</td>";
echo "<td> $rows[$username]</td>";
echo "<td> $rows[$password]</td>";
echo "<td> $rows[$role_name]</td>";
?>
<div id = "edit">
<td> <button type='button' id="<?php $rows[$user_id];?>" onclick="submit_id()"> Edit </button> </td>
</div>
<?php
}
echo "</table>"; ?>
<script>
function submit_id() {
var user_id = user_id.val();
$.ajax({
url:'reedit.php',
type: 'GET',
data: (user_id);
})
}
</script>
I want to have each edit button, to change only the row that it is aligned to.
I saw that you had jQuery at least..
I think this will help you a LOT:
<?php
$sql_query = "SELECT User.user_id,User.name,User.surname,User.username,User.password,Role.role_name FROM User INNER JOIN Role ON User.role_id = Role.role_id";
$result = mysqli_query($conn, $sql_query);
if(!$result) {
die(mysqli_error($conn));
}
$table_html = "<table id=\"usersTable\">";
while($rows = mysqli_fetch_array($result)) {
$table_html .= "<tr>";
$table_html .= "<td>" . $rows["user_id"] . "</td>";
$table_html .= "<td>" . $rows["name"] . "</td>";
$table_html .= "<td>" . $rows["surname"] . "</td>";
$table_html .= "<td>" . $rows["username"] . "</td>";
$table_html .= "<td>" . $rows["password"] . "</td>";
$table_html .= "<td>" . $rows["role_name"] . "</td>";
$table_html .= "<td><button type=\"button\" class=\"editBnt\">Edit</button></td>";
$table_html .= "</tr>";
}
$table_html .= "</table>";
echo $table_html;
?>
<script>
$(function() {
$("#usersTable").on("dblclick", "td td:not(:first-child) td:not(:last-child)", function() {
$(this).html("<input type=\"text\" class=\"form-control dynamicInput\" value=\""+$(this).text()+"\"></input>").children("input").focus();
$(this).on("change blur", "input.dynamicInput", function() {
$(this).parent("td").text($(this).val());
});
});
$("#usersTable").on("click", "button.editBnt", function() {
var row = $(this).parent().parent(),
user_data = {
user_id: row[0].cells[0].innerText,
name: row[0].cells[1].innerText,
surname: row[0].cells[2].innerText,
username: row[0].cells[3].innerText,
password: row[0].cells[4].innerText,
role_name: row[0].cells[5].innerText
};
alert("You can now save the data or do what ever you want here.. check your console.");
console.log(user_data);
});
});
</script>
you can use the content-editable attribute to make your cells editable
something like:
var rows = document.querySelectorAll("tr");
row.foreach(function() {
this.addEventListener('click', function() {
this.setAttribute('contenteditable','contenteditable');
});
});
You will want to put the click listener on your button instead of the row
I possible to insert update.php?id=" . $row["id"] . " into AJAX url?
I'm trying to make async sql row updating via form. I don't have specific id, because id is called on click.
JS
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
$.ajax({
type: "POST",
url: 'update.php?id=" . $row["id"] . "',
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
PHP where update.php call is located
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
$potnik = $row["potnik"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form id='form' action='update.php?id=" . $row["id"] . "' method='POST'><input id='id' name='potnik' value='".$row["id"]."' type='hidden' /> <input id='cas' class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input id='submit' type='submit' value='Posodobi'> <label id=\"info\"></label></form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
First, you will want to fix a lot of your HTML. You have many repeating ID attributes for various HTML elements. This will cause many JavaScript issues and is incorrect syntax for HTML.
$html = ""
$id = $row['id'];
if ($row["naslov"] !== null) {
$html .= "<div class='col-6 flex-vcenter-items fs-1'>\r\n";
$html .= "\tNastavi uro\r\n";
$html .= "\t<form id='form-$id' action='update.php?id=$id' method='POST' data-id='$id'>\r\n";
$html .= "\t\t<input id='cas-$id' class='form-control fancy-border' type='text' name='posodobljeni_cas' />\r\n";
$html .= "\t\t<input id='submit-$id' type='submit' value='Posodobi'> <label id='info-$id'></label>\r\n";
$html .= "\t</form>\r\n</div>\r\n";
$html .= "</div>";
echo $html;
} else {
echo " </div>";
}
You can see a lot being done here. First we create a $html and $id variable to just make things easier. Now when we enter String data into the $html variable, if we're using " (double quote) for wrapping, we can just use $id directly in the string. We will also use ' (single quote) for wrapping all the HTML Element attributes.
Try this for your jQuery:
$(function(){
$("form[id|='form']").on('submit', function(e) {
e.preventDefault();
var form = $(this);
var id = form.data("id");
var cas = $("inptu[id|='cas']", form);
var info = $("input[id|='info']", form);
if(validate()) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
});
More Info on the selector: https://api.jquery.com/attribute-contains-prefix-selector/
Unable to test this as you have not provided a testing area. Hope it helps.
You can assign the PHP $row['id']; variable to a local JS variable and append it to the URL as shown below -
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
var id=<?=$row['id'];?>;
$.ajax({
type: "POST",
url: 'update.php?id='+id,
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
Have been searching around for a while and can't find a proper answer to this problem. I have a "finance" tracker that has several hidden divs which using jQuery appear when the button to show that div is clicked. I have a Asset Tracker which queries a database and upon being checked updates the database with new values in adjacent input rows where the checkbox is located. I am trying to get the checkbox to submit the data without causing the page to reload and the div to "toggle" off again.
On the form section I attempted to remove the method='post' but instead when checking the box it reloaded the page and added all the post variables to the URL string. I removed the action='FBook.php' in an attempt to prevent the reloading, but that did not resolve the problem.
Here is the related code from the PHP file:
if(isset($_POST['AssetSetUpdate'])) { $AssetLastUpdate = $dtNowDate->format('Y-m-d');
foreach($_POST['AssetID'] as $key => $id) { if(isset($_POST['AssetSetUpdate'][$key])) {
$stmt_ATrackUp -> bindParam(':UpDate', $AssetLastUpdate, PDO::PARAM_STR, 10);
$stmt_ATrackUp -> bindParam(':UpNotes', $_POST['AssetNotes'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpThis', $_POST['AssetDescription'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpVal', $_POST['AssetValue'][$key], PDO::PARAM_INT, 3);
$stmt_ATrackUp -> execute(); } else continue; }
echo "<div class='Notice'>" . $PageTitle . " / Assets updated!</div>"; }
(other code)
$(document).ready(function() {
$("#AssetUpdateForm").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'FBook.php',
data: $(this).serialize(),
success: function() { alert('form submitted'); },
});
return false;
});
$('#ShFBAsset').click(function() { $('#FBAsset').toggle('slow'); });
(other code)
});
(other code)
$AssetCounter = 1;
$stmt_ATrack -> execute(); while ($row_ATrack = $stmt_ATrack -> fetch(PDO::FETCH_ASSOC))
{
$ChAge = $row_ATrack['Checked']; $cChAge = ''; switch(true)
{
case (strtotime($ChAge) >= strtotime('-7 days')): $cChAge = 'FBCAN'; break;
case (strtotime($ChAge) >= strtotime('-30 days')): $cChAge = 'FBCA1'; break;
case (strtotime($ChAge) >= strtotime('-90 days')): $cChAge = 'FBCA3'; break;
default: $cChAge = 'FBCA6'; break;
}
if(isset($row_ATrack['Serial'])) { $IfDSerial = "<strong>Serial: </strong>" . $row_ATrack['Serial'] . "<br/>"; } else { $IfDSerial = ''; }
if(isset($row_ATrack['UPC'])) { $IfDUPC = "<strong>UPC: </strong>" . $row_ATrack['UPC'] . "<br/>"; } else { $IfDUPC = ''; }
if(isset($row_ATrack['Related'])) { $IfDRelated = "<strong>Related: </strong>" . $row_ATrack['Related'] . "<br/>"; } else { $IfDRelated = ''; }
if(isset($row_ATrack['Location'])) { $IfDLocation = "<strong>Location: </strong>" . $row_ATrack['Location'] . "<br/>"; } else { $IfDLocation = ''; }
if(isset($row_ATrack['TagPhoto'])) { $IfDTagPhoto = "<strong>Tag photo: </strong><a href='Images/INV/" . $row_ATrack['TagPhoto'] . ".JPG'>" . $row_ATrack['TagPhoto'] . "</a><br/>"; } else { $IfDTagPhoto = ''; }
$IfDetails = "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'>" . ($IfDSerial) . ($IfDUPC) . ($IfDRelated) . ($IfDLocation) . ($IfDTagPhoto) . "</div></div>";
if($IfDetails == "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'></div></div>") { $IfDetails = ''; }
echo "<form id='AssetUpdateForm[" . $AssetCounter . "]' method='post'>";
echo "<tr><input type='hidden' name='AssetID[" . $AssetCounter . "]' value='" . $AssetCounter . "' />";
echo "<td><input type='hidden' name='AssetDescription[" . $AssetCounter . "]' value='" . $row_ATrack['Description'] . "' /><a href='https://www.google.com/#q=eBay+" . $row_ATrack['Description'] . "' target='_new_AssetSearch'>" . $row_ATrack['Description'] . "</a></td>";
echo "<td>" . $row_ATrack['Type'] . " - " . $row_ATrack['Category'] . "</td>";
echo "<td><input type='checkbox' name='AssetSetUpdate[" . $AssetCounter . "]' value='Now' onchange='this.form.submit();' /></td>";
echo "<td><input type='number' name='AssetValue[" . $AssetCounter . "]' value = '" . $row_ATrack['Value'] . "' style='width: 75px;' /></td>";
echo "<td class='" . $cChAge . "'>" . $ChAge . "</td>";
echo "<td><input type='text' name='AssetNotes[" . $AssetCounter . "]' value = '" . $row_ATrack['Notes'] . "' style='width: 140px;' /></td>";
echo "<td>" . $IfDetails . "</td>";
echo "</tr>";
echo "</form>";
$AssetCounter++;
}
Your JavaScript:
$("#AssetUpdateForm")
… is working on a form with id="AssetUpdateForm".
Your PHP says:
id='AssetUpdateForm[" . $AssetCounter . "]'
which in HTML terms becomes:
id='AssetUpdateForm[something]'
Even if the variable is empty, you still have the square brackets, so the ID is not going to match and the JavaScript event handler will never be bound to that element.
You need to either use the real ID or, since it appears that it can change, add a class to the form and use a .class-selector in the JavaScript.
NB: Your HTML is invalid. The particular problem you have has the potential to cause the same symptoms are you describe so just fixing the problem above might not be enough. Use a validator and write valid HTML too.
Had nothing to do with the HTML or PHP. Turns out that jQuery AJAX was conflicting with the onclick='this.form.submit();' property. I removed that and changed the ajax request to the following - and while it still has bugs as it won't work on the 2nd ajax request, it validates everything else is fine.
$(".Check2Update").on('change', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'FBook.php',
data: $(this.form).serialize(),
success: function(html) {
console.log('Successfully submitted AJAX!');
$("#TableAssets").replaceWith($('#TableAssets', $(html)));
}
});
});
I am trying to delete record from database using AJAX. The confirmation window does not appear so that the record can be deleted. here is the code..
<?php
$q = $_GET['q'];
$p = $_GET['p'];
$sql="SELECT * FROM course_details WHERE sem='" . $q . "' AND branch='" . $p . "' ORDER BY course_codes ASC";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
echo '<tr class="record">';
echo "<td>" . $row['course_codes'] . "</td>";
echo "<td>" . $row['course_names'] . "</td>";
echo "<td>" . $row['course_instructors'] . "</td>";
echo "<td>" . $row['course_credits'] . "</td>";
echo '<td><div align="center">delete</div></td>';
echo '</tr>';
}
echo "</table>";
mysql_close($bd);
?>
Here $p and $q are send by an AJAX script from another page. It is working fine. The records are displayed as expected. Deletion works using AJAX if i do not use AJAX to display records.The script I am using to delete is:
<script src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?")){
$.ajax({
type: "GET",
url: "deleteCourse.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
deleteCourse.php
if($_GET['id']){
$id=$_GET['id'];
$id = mysql_escape_string($id);
}
$del = "DELETE from course_details where course_id = '$id'";
$result = mysql_query($del);
The problem is because you are creating dynamic elements so you have to use a delagate $(document).on() inorder to bind the click event to the elements.
Here is the corrected code
<script type="text/javascript">
$(function() {
$(document).on('click','.delbutton',function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?")){
$.ajax({
type: "GET",
url: "deleteCourse.php",
data: info,
success: function(){ }
});
}
return false;
});
});
</script>
and your deletCourse.php
if($_GET['id']){
$id=$_GET['id'];
$id = mysql_escape_string($id);
}
$del = "DELETE from course_details where course_id = ".$id."";
$result = mysql_query($del);
Hope this helps, Thank you
try this one
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
delete
delete
delete
delete
delete
javascript
function del(id)
{
var info = 'id=' + id;
if(confirm("Are you sure you want to delete this Record?")){
var html = $.ajax({
type: "POST",
url: "delete.php",
data: info,
async: false
}).responseText;
if(html == "success")
{
$("#delete").html("delete success.");
return true;
}
else
{
$("#captchaStatus").html("incorrect. Please try again");
return false;
}
}
}
ajax file
if($_GET['id']){
$id=$_GET['id'];
$id = mysql_escape_string($id);
}
$del = "DELETE from course_details where course_id = '$id'";
$result = mysql_query($del);
if($result)
{
echo "success";
}
Try this:
<script type="text/javascript" src="jquery.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function del(id)
{
var info = 'id=' + id;
if(confirm("Are you sure you want to delete this Record?")){
var html = $.ajax({
type: "GET",
url: "deletCourse.php",
data: info,
async: false ,
success: function() {
window.location.reload(true);}
}).responseText;
}
}
</script>
<?php
$link=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("cart");
$sql=mysql_query("SELECT * FROM `details`");
echo "<table>";
echo "<tr><th>Name</th><th>NO of Items</th></tr>";
while($row = mysql_fetch_assoc($sql)){
echo '<tr class="record">';
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['num'] . "</td>";
echo '<td><div align="center">delete</div></td>';
echo '</tr>';
}
echo "</table>";
mysql_close($link);
?>
i have problem with ajax post with form submit event. i have table generated by opentable.php
here code for opentable.php
<?php
session_start();
require("dbc.php");
$memberid = $_SESSION['memberid'];
$sql = "SELECT * FROM `open` WHERE `memberid`='$memberid'";
$mydata = mysql_query($sql);
echo "<table><tr><th>Time</th><th>Type</th><th>Size</th><th>Price</th><th>Profit</th><th></th><th></th></tr>";
while($record = mysql_fetch_array($mydata)){
echo "<form action = assets/close.php id=closeform>";
echo "<tr>";
echo "<td>" . $record['opendate'] . "</td>";
echo "<td>" . $record['type'] . "</td>";
echo "<td>" . $record['size'] . "</td>";
echo "<td>" . $record['openprice'] . "</td>";
echo "<td>" . $record['profit'] . "</td>";
echo "<td>"."<input type=hidden name=openid value=".$record['openid']." </td>";
echo "<td>" . "<input type=submit name=close value=close". " </td>";
//echo "</tr>";
echo "</form>";
}
echo "</table>";
?>
and ajax javasript for submit event trade.js
$(document).ready(function() {
$('#closeform').submit(function( event ) {
event.preventDefault();
var $form = $( this ),
price = $('#price').val(),
id = $form.find( "input[name='openid']" ).val(),
url = $form.attr( "action" );
var posting = $.post( url, { openid: id, closeprice: price } );
var r=confirm("Are you sure?");
if(r =true){
posting.done(function( data ) {
alert(data);
});
}
else
{
alert("Transaction canceled")
}
});
}
i tested it, and it runs like normal php form. and error there is no $_POST data passed.
please give me recomendation for this kind of event thanks.
closeform is a dynamically added form, try using .on():
$(document).on('submit', '#closeform', function ( event ) {