[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
Related
I am making a cart-mechanism with jquery, ajax and php. The problem is that the text in the html element aren't getting appended to the session array. This is my ajax code:
$(document).ready(function(){
$("#cart").on("click", function(){
var name = $("#name").text();
var cost = $("#cost").text();
$.ajax({
type:"post",
data:"name="+name+"&cost="+cost,
url:"senddata.php",
success:function(data){
$("#info").html(data);
}
});
});
});
This is my html displayed with php:
function getData()
{
require_once('../config.php');
$query = mysqli_query($conn, "SELECT p_name, p_cost, p_pic, p_desc FROM products");
while($row = mysqli_fetch_assoc($query))
{
echo "<form><tr>";
echo "<td id='name' name='name'>" . $row['p_name'] . "</td>";
echo "<td id='cost' cost='cost'>" . $row['p_cost'] . "</td>";
echo "<td>" . $row['p_pic'] . "</td>";
echo "<td>" . $row['p_desc'] . "</td>";
echo "<td id='cart'><input type='button' id='submit' value='Add To Cart'></td><tr></form>";
}
mysqli_close($conn);
}
And finally, this is where I have stored the ajax variables in a session array:
session_start();
$_SESSION['cart_name'] = array();
array_push($_SESSION['cart_name'], $_POST['name']);
var_dump($_SESSION['cart_name']);
$_SESSION['cart_cost'] = array();
array_push($_SESSION['cart_cost'], $_POST['cost']);
var_dump($_SESSION['cart_cost']);
I am getting no error whatsoever but the items get appended to the array the first time, but after that, the variables don't get appended at all.
Variables does not appended because you initialize every time the
$_SESSION['cart_name'] = array();
$_SESSION['cart_cost'] = array();
That means that every time before you push the new data you empty the SESSION var.
I have a problem in which I cannot solve. I have a simple page where I query all Users and list them in a table. When a user clicks on one of the table rows, it should be taken to another page where the user can edit information of the that they picked. The problem is that in my script, the $_POST value is always the value of the last
CODE
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub();'>";
echo "<td>";
echo $assoc['UserID'];
echo "<input type = 'hidden' name = 'UserID' value = '". $assoc['UserID'] ."' />";
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(){
document.getElementById("edit").submit();
return false;
}
</script>
I've slightly modified your code - this should work:
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub(". $assoc['UserID'] .");'>";
echo "<td>";
echo $assoc['UserID'];
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(UserID){
document.location.href = 'http://www.yourdomain.com/something.php?UserID='+UserID;
return false;
}
</script>
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"
please in need help in updating multiple rows based on dynamic data fetched from mysql database. I have implemented this using $_Post to udate.php file, but how can i do this using ajax.
//THIS SCRIPT FETCH FROM DATABASE
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("student") or die("Unable to select database");
$sql = "SELECT * FROM students ORDER BY id";
$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$i = 0;
echo '<table width="50%">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>Name</td>';
echo '<td>Address</td>';
echo '</tr>';
echo "<form name='form_update' method='post' action='update.php'>\n";
while ($students = mysql_fetch_array($result)) {
echo '<tr>';
echo "<td>{$students['id']}<input type='hidden' name='id[$i]'value='{$students['id']}' /></td>";
echo "<td>{$students['name']}</td>";
echo "<td><input type='text' size='40' name='address[$i]' value='{$students['address']}' /></td>";
echo '</tr>';
++$i;
}
echo '<tr>';
echo "<td><input type='submit' value='submit' /></td>";
echo '</tr>';
echo "</form>";
echo '</table>';
echo $i; ?>
</body>
// HERE IS THE UPDATE SCRIPT
// On clicking submit all rows are updated but i still cant achieve dis with ajax.
UPDATE.PHP
$size = count($_POST['address']);
$i = 0;
while ($i < $size) {
$address= $_POST['address'][$i];
$id = $_POST['id'][$i];
$query = "UPDATE students SET address = '$address' WHERE id = '$id' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
echo "$address<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
?>
HERE IS WHAT I HAVE TRIED ON AJAX
function update(){
var j=0;
while(j< <?php echo $i ; ?>){
var id=$("#id" + j);
var address=$("#address" + j);
$.ajax(
{
url:"update.php",
type:"post",
data:{id:id.val(),address:address.val()},
success:function(response)
{
}
});
}
ANY HELP WILL BE APPRECIATED
You shouldn't need to loop and execute multiple POSTs. Simply serialize the form data and send it to the script, e.g.:
$.ajax({
url: 'update.php',
type: 'post',
data: $('#your-form-id').serialize(),
success:function(response){
// do something
}
});
Also, you should consider revising your PHP to prevent SQL injection: How can I prevent SQL injection in PHP?
I'm not very good at JavaScript but here is my problem.
I have three pages: page1.php, page2.php, page3.php
On page1.php, I have a form for users to select grade level they want to view, then the action is performed on page2.php -- displaying the list of all students in that grade.
This is the code for page2.php
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$level = $_POST['level_group'];
$room = $_POST['room_group'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT std_id, std_name FROM students WHERE std_level LIKE '$level%' AND std_room LIKE '$room';");
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Action</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo"<form action='view_one_student.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td>" . '<input type="submit" value="view"> <input type="submit" value="sdq">' . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
The question...now is How can I write the code on page3.php so that when users clicks on view or sdq button next to each column, the student ID should be captured, send a request to the database, and query other data related to this particular student such as age, address, phone..etc. and display them on that page3.php
page2.php
You have to add a hidden input with the id of the student in page2.
<input type="hidden" value="'.$row["std_id"].'" name="std_id">
Change your action page to page3 (if that's where you want to display the student info: name, age...)
<form action='page3.php' method='post'>page2.php
The code for page2:
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$level = $_POST['level_group'];
$room = $_POST['room_group'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT std_id, std_name FROM students WHERE std_level LIKE '$level%' AND std_room LIKE '$room';");
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Action</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo"<form action='page3.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td> <input type='hidden' value='" . $row["std_id"] . "' name='std_id'>";
echo "<input type='submit' value='view'>";
echo "<input type='submit' value='sdq'></td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
page3.php
A posible solution for page3 can be: (add your columns you need: age, address, phone..)
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$id = $_POST['std_id'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM students WHERE std_id ='$id';");
echo '<h3>Student detail</h3>';
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Age</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td>" . $row['std_age'] . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
You can modify your code like this. A hidden field will send the student id to the page of view_one_student.php.
while($row = mysqli_fetch_array($result))
{
echo"<form action='view_one_student.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo '<input type="hidden" value="'.$row["std_id"].'" name="std_id">';
echo "<td>" . '<input type="submit" value="view"> <input type="submit" value="sdq">' . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
On view_one_student.php you have to catch that with:
$_POST["std_id"]
And eventually input that into a sql sentense in view_one_student.php:
$sql = "SELECT * FROM <table> WHERE id=".$_POST["std_id"];
Thats the general idea.