I have a contenteditable table which when edited should update a table in the database via ajax but nothing is happening to the database when I change the values.
<div id="activities2" class="activities2"> <?
$q2a="SELECT activityid, activitynumber, title, description, leaders, time FROM activities where activities.meetingid='$id' AND activities.unitid='$input2'";
$r2a=mysqli_query($dbc,$q2a) or die(mysqli_error($dbc));
echo "<table class='layouttable'><tr><td>ActivityNumber</td><td>Title</td><td>Description</td><td>Leaders</td><td>Time</td><td>Edit</td>";
while($row2a
=mysqli_fetch_assoc($r2a))
{
echo "
<tr>
<td contenteditable='true' id='activitynumber:" . $row2a['activityid'] . "'>" . $row2a['activitynumber'] . "</td>
<td contenteditable='true' id='title:" . $row2a['activityid'] . "'>" . $row2a['title'] . " </td>
<td contenteditable='true' id='description:" . $row2a['activityid'] . "'>" . $row2a['description'] . " </td>
<td contenteditable='true' id='leaders:" . $row2a['activityid'] . "'>" . $row2a['leaders'] . " </td>
<td contenteditable='true' id='time:" . $row2a['activityid'] . "'>" . $row2a['time'] . " </td>
</tr>.
";
}
echo"</table>"; ?><br><Br></div>
The javascript for ajax is:
<script name = 'inlineedit'>
$(document).ready(function(){
$("td[contenteditable=true]").blur(function(){
var msg = $(".alert");
var newvalue = $(this).text();
var field = $(this).attr("id");
$.post("activityupdate.php",field+"="+newvalue,function(d){
var data = JSON.parse(d);
msg.removeClass("hide");
if(data.status == '200'){
msg.addClass("alert-success").removeClass("alert-danger");
}else{
msg.addClass("alert-danger").removeClass("alert-success");
}
msg.text(data.response);
setTimeout(function(){msg.addClass("hide");},3000);//It will add hide class after 3 seconds
});
});
});
</script>
and the php file doing the editing (though it doesnt seem to be getting this far is:
<?
$response = NULL;
$status = http_response_code(406);
if(!empty($_POST)){
include "connect_db.php"; //Including Database Settings
foreach($_POST as $key=>$value){
$key = strip_tags(trim($key));
$value = strip_tags(trim($value));
$explode = explode(":",$key);
$activity_id = $explode[1];
$field_name = $explode[0];
if(isset($activity_id)){
$query = "UPDATE activities SET $field_name='{$value}' WHERE activityid='$activity_id'";
$update = mysqli_query($dbc,$query) or die(mysqli_error($dbc)); //Update the activity Table
if($update){
$response = "User Details Updated";
http_response_code(200); //Setting HTTP Code to 200 i.e OK
}else{
$response = "Not Modified";
http_response_code(304); //Setting HTTP Code to 304 i.e Not Modified
}
}else{
$response = "Not Acceptable";
}
}
}
echo json_encode(array(
"status"=>$status,
"response"=>$response
));
?>
You would need few changes in code:
Instead of setting contenteditable='true' use class='editable'.
in the js try using on change instead of blur.
$("td.editable").on ("change",function(){....
this would execute ajax on every change in the editable fields.
Related
[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples
I am trying to create a table which pulls data from an SQL database and each row on the table is a clickable link to it's corresponding page depending on the first column data in the database.
I have managed to do both parts separately i.e create a table with SQL data and i've managed making a table with each row a clickable link however I am struggling to combine the two.
I am using a .js to listen for clicks and send you off depending on the "tr data-href='url'".
My php script to create the table form SQL data creates the "tr" first, then populates the row with each cell, closes the "/tr" and repeats for all rows.
How can I make the php write the "tr data-href='url'" where 'url' is the same as the first column of data for each row?
My PHP script is below, followed by the five lines of JS.
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$db_name = "FFD";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT id,name,location,plots,blurb FROM Sites");
$all_property = array(); //declare an array for saving property
//showing property
echo '
<div class="content-container">
<h1>Table heading</h1>
<section>
<div class="tbl-header">
<table cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<th>' . $property->name . '</th>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>
</thead>
</table>
</div>
<div class="tbl-content">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>';
//end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo '</tbody></table></div></section></div>';
?>
$(document).ready(function(){
$('tr[data-href]').on("click", function() {
document.location = $(this).data('href');
});
});
I could just be thick and missing something simple and obvious.
Thanks in advance!
You can concatenate your url, like this (assuming id is the column with the url)
while ($row = mysqli_fetch_array($result)) {
echo '<tr data-href="' . $row['id'] . '">';
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>';
}
echo '</tr>';
}
I have created a while loop for the data fetched from the database. I have added a button to each loop. when the user clicks on the button, it should open a new tab and since I am using the form method="GET" the data is getting passed to the new tab window.
This is not working only for the first loop button, whereas it is working fine for all other buttons created by the loop. Can someone help? The code is as below:
$result = mysqli_query($link, $query);
if ($result->num_rows > 0) {
// output data of each row
$row = 1;
$number = 1;
while($row = $result->fetch_assoc()) {
echo '<tr>';
$invoiceNumber = $row["invoiceNumber"]`enter code here`;
echo ' <td align="center" style="text-align:center">' . $invoiceNumber . '</td>';
echo ' <td align="right">' . $row["invoiceDate"] . '</td>';
echo ' <td align="right">' . $row["accountName"] . '</td>';
$beginTime = $row["beginTime"];
$beginTime = date("D, j M Y", strtotime($beginTime));
echo ' <td align="right">' . $beginTime . '</td>';
$endTime = $row["endTime"];
$endTime = date("D, j M Y", strtotime($endTime));
echo ' <td align="right">' . $endTime . '</td>';
echo ' <td align="center"style="text-align:center"><form method = "GET" action= "invoice.php" name="'.$number.'"><button name= "invoice" value='.$invoiceNumber.'></form>View</button></td>';
echo '</tr>';
$number = $number + 1;
}
} else {
echo "0 results";
}
Saw that the form closing tag </form> is inside the <button> tag, would you try to change it to:
<td align="center"style="text-align:center">
<form method = "GET" action= "invoice.php" name="'.$number.'">
<button name= "invoice" value='.$invoiceNumber.'>View</button>
</form>
</td>
See if it helps..
I edited the code and removed the form tag. It works perfectly for all buttons now including the first button in while loop. Code is as below :
echo ' <td align="center"style="text-align:center"><button id="invoice" name= "invoice[]" value='.$invoiceNumber.'>View</button></td>';
<?php
if ($_POST['invoice']) {
$name = $_POST['invoice'];
$array = $name[0];
//echo $array;
echo '<script>window.open("invoice.php?'.$array.'","_blank")</script>';
}
?>
I am trying to remove to this table on successful delete from an AJAX to PHP call.
Below is the function ,
list.php
<script type="text/javascript">
function massDelete()
{
if (!confirm("Are you sure"))
{
return false;
}
else
{
var selecedids = $("#selectedids").val();
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("success").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_delete.php?massDelete=" + selectedids.value, true);
xhttp.send();
}
}
return false;
}
</script>
the above code successfully gives me the selected ID for deletion
on this PHP side which is on another File
ajax_delete.php
<?php
if (!empty($_REQUEST['massDelete'])) {
$selectId = $_REQUEST['massDelete'];
$finalId = ltrim($selectId, ",");
$sql = mysql_query("delete from contact_form where contactUser_id in ($finalId)", $con);
if ($sql) {
// echo '<script>';
//echo 'var parent = document.getElementById("fullTable")';
//echo 'element.remove(parent)';
//echo '</script>';
echo "sucess deleted";
} else {
echo "Please select a Contact to delete";
}
}
?>
The response does give me the successful message, but somewhere I want to disappear the below HTML table in response
list.php
<?php
echo '<table id="fullTable">';
echo "<tr><td> ";
echo '<input type="checkbox" name="checkAll" id="checkAll"/></td>';
echo '<td colspan="8" align="right">';
echo '<button type="submit" onClick="return massDelete()" name="delete" class="deleteall" id="deleted">Delete All</button></td>';
echo "</tr>
<tr>
<th></th>
<th>FIRST NAME</th>
<th>LAST NAME</th>
<th>EMAIL</th>
<th>PHONE</th>
<th>FAX</th>
<th></th>
<th></th>
<th></th>
</tr>";
while ($row = mysql_fetch_array($results)) {
echo '<div id="checkboxlist">';
echo '<tr class="show">';
echo '<td><input name="checkbox[]" type="checkbox" class="checkbox1" value="' . $row['contactUser_id'] . '" id="Checkbox1"></td>';
echo '<td>' . $row['first_name'] . '</td>';
echo '<td>' . $row['last_name'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>' . $row['phone'] . '</th>';
echo '<td>' . $row['fax'] . '</td>';
echo '<td>Edit</td>';
echo '<td><a class="delete" href="#" id="' . $row['contactUser_id'] . '">Delete</a></td>';
echo '<td>View</td>';
echo '</div>';
}
} else {
echo '<td colspan="9"><h1>No contacts found.</td></h1>';
}
?>
I am confused to what should I do so that if one row is deleted than only that row disappears,
but if all the checkboxes are selected for deletion, than on sucess, tha whole table should disappear..
So it sounds like the php successfully deletes it since when you refresh the page the correct data shows up.
But if the page has to be refreshed for it to show up properly, you need to make sure you are returning the correct information, and parsing it correctly. Just console.log() the response xhttp.responseText, and see if the correct data is returned, and then double check you are parsing it correctly (changing the dom appropriately).
You don't need to refresh your page to show it's correct. You need to use javascript to remove the row on success. Here's the basics:
var deletedRow = $('#fullTable');
$.post('script.php', {data:data}, function(){
if(data == "success"){
deletedRow.remove(); //This will remove the row from the view
}
});
Ajax can return a call and you give a statement that shows if success, you have to have javascript actually delete it. Yes, we know it's removed from the database, so you can successfully remove the view from the page.
UPDATE This is using jQuery, not pure javascript. But it's only an example to show that you need to delete the element using javascript and it won't just disappear because it's not in your database anymore.
Finally after referring to this remove any element using Jquery
I found the solution, and I also changed the AJAX function code which is mentioned below,
function massDelete()
{
var element = $(this);
var selecedids = $("#selectedids").val();
var info = 'massDelete=' + selectedids.value;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "ajax_delete.php",
data: info,
success: function(){
}
});
$this.parent("#fullTable").load("list.php");
}
return false;
}
the $this.parent("#fullTable").load("list.php"); statement reloaded that table hence reflecting only those information which are present in the database.
Right now I have a grid and each grid part/bit contains an image, the name of the item and different buttons that can delete the item from the mysql database and update the price. What I want to do know is that when a user say clicks on the image a window would pop up where extra information would be displayed. However it is not a pop up in a usual sense that it would create another window but rather a pop up within the current window/tab. E.g. When you press on a photo in Facebook it creates almost like a popup on which you can comment or change to the next photo. Does anyone have any idea on how to do this or at least what is the whole thing/process called?
Sorry if I can't give a proper name but I don't know it myself :/
Here is the code to what I have now. I would prefer an actual code solution but if you can lead me to where I should look for it I would also be happy. I tried looking online however everything I get is window pop ups.
<div class="boxes">
<?php
$ID = $_SESSION['SESS_MEMBER_ID'];
$con = mysql_connect("", "", "");
if (!$con){
die("Cannot connect: " . mysql_error());
}
mysql_select_db("test", $con);
$sql = "SELECT * FROM items WHERE member_id = $ID";
$myData = mysql_query($sql, $con);
$dir = 'Images';
$symbol = '\\';
$end = 'r.jpg';
$currency = '£';
while($record = mysql_fetch_array($myData)) {
$real_name = str_replace('_', ' ', $record['Name']);
$result = $dir . $symbol . $record['Name'] . $end;
$value = $currency . $record['price_now'];
$link = $record['url'];
echo "<div class = frame>";
echo "<div class = bit-3>";
echo "<div class = box>" . "<img src=" . $result . " alt=some_text>";
echo "<br />";
echo "<br />";
echo $real_name;
echo "<br />";
echo "<br />";
echo "Price now: " . $value;
echo "<form action = member-profile-page.php method = post>";
echo "Desired price: ";
echo "<td>" . "<input type = text name = desired_price value = " . $record['desired_price'] . " </td>";
echo "<td>" . "<input type = hidden name = hidden value = " . $record['Id'] . " </td>";
echo " ";
echo "<td>" . "<input type = submit name = update value = Update" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = delete value = Delete" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = buy value = Buy" . " </td>";
echo "</form>";
echo "</div>";
echo "</div>";
echo "</div>";
}
if (isset($_POST['buy'])){
$query = "select url from items where Id = '$_POST[hidden]'";
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
$code = $row['url'];
echo "$code";
header("Location: $code");
}
};
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE items SET desired_price = '$_POST[desired_price]' WHERE Id = '$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if (isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM items WHERE Id = '$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
mysql_close($con);
?>
</div>
Sounds like you're looking for an overlay:
http://jquerytools.org/demos/overlay/index.html
or a modal:
https://jqueryui.com/dialog/
These are by no means the only examples; there are hundreds of such solutions. These will get you started, though. Good luck!
What you think about is just a layer in the current browser viewport, having some controls to let the user handle it like a "desktop window".
There are quite a lot of JS frameworks offering handy solutions for this, i.e. jQuery UI. Within there, look for "dialog"