How to delete/edit sql entry using PHP and AJAX? - javascript

I'm learning PHP and SQL and as exercise I'm working on a page that is actually something like admin panel for a website that lists movies. I'm using lampp and phpmyadmin where I have created a simple database that contains two tables, movie list and users list.
Because I'm beginner and my code is probably messy, I'm describing what I tried to achieve. There's login.php page where the only functionality is typing username and password. If info matches info from SQL table, user proceeds to adminpanel.php.
This page should load a list of movies and create a table with that data. At the end of each row I want two buttons, edit and delete. What I'm trying to achieve is to delete current row where delete button is clicked, for delete button. Edit button should show hidden form just for the row where button was clicked. This form would contain button that actually updates data in SQL table after filling form and clicking the button. (I haven't added function that shows form yet, I care about buttons much more) Form for adding movies at the end of the file works.
Here's adminpanel.php
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript" src="changes.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></script>
<style type="text/css">
*{text-align: center;}
.skriveni_input{
display: none;
};
</style>
</head>
<?php
require_once('connection.php');
if(!isset($_POST['btnlogin'])){
exit;
}
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT usrname,password FROM usrs WHERE usrname='$username' AND password='$password' ";
$res = mysqli_query($conn,$query);
$rows = mysqli_num_rows($res);
if($rows == 1){
echo "Welcome ".$_POST['username']."<br><br>";
} else {
echo "<script>
alert('Wrong login info');
window.location.href='login.php';
</script>";
exit;
}
$query = "SELECT * FROM movies";
$result = $conn->query($query);
echo "<table align = center cellspacing = 0 border = 0;><thead><tr><th>Name</th><th>Year</th><th>Genre</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo '<td id="row_id" style="display:none;" value="'.$row["movie_id"].'">'.$row["movie_id"].'</td>';
echo '<td>'.$row["name"].'</td>';
echo '<td>'.$row["year"].'</td>';
echo '<td>'.$row["genre"].'</td>';
echo '<td><input type="submit" name="edit" value="edit" data-index="' . $row['movie_id'] . '" class="btnedit" id="btnedit"></input></td>';
echo '<td><input type="submit" name="delete" value="delete" class="btndlt" id="btndlt"></input></td>';
echo "</tr>";
echo "<tr>
<td><input type='text' class='hidden_input' id='hidden_name" . $row['movie_id'] . "'placeholder='hidden name'></input></td>
<td><input type='text' class='hidden_input' id='hidden_year" . $row['movie_id'] . "'placeholder='hidden year'></input></td>
<td><input type='text' class='hidden_input' id='hidden_genre" . $row['movie_id'] . "'placeholder='hidden genre'></input></td>
</tr>";
}
echo "</tbody></table>";
?>
<h3>Add movie form: </h3>
<form action="" method="POST">
<label for="movie_name">Movie name : </label>
<input type="text" name="movie_name" id="movie_name">
<br><br>
<label for="movie_year">Year: </label>
<input type="text" name="movie_year" id="movie_year">
<br><br>
<label for="movie_genre">Genre: </label>
<input type="text" name="movie_genre" id="movie_genre">
<br><br>
<input type="submit" name="submit_movie" id="submit_movie" value="Submit">
</form>
</html>
Here's my javascript file with ajax calls:
$(document).ready(function(e){
$('#submit_movie').click(function(e){
e.preventDefault();
var movie_name = $('#movie_name').val();
var movie_year = $('#movie_year').val();
var movie_genre = $('#movie_genre').val();
$.ajax({
type: 'POST',
data: {movie_name:movie_name, movie_year:movie_year, movie_genre:movie_genre},
url: "insert.php",
success: function(result){
alert('Movie ' + movie_name + ' (' + movie_year + ')' +' added successfully.');
document.location.reload();
}
})
});
$('.btnedit').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().html();
alert(id);
//unfinished function
})
$('.btndlt').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().prev().html();
e.preventDefault();
$.ajax({
type: 'POST',
data: {id:id},
url: 'delete_row.php',
success: function(result){
alert('Successfully deleted.');
document.location.reload();
}
})
})
});
Here's php page for adding a movie, insert.php (this one works, posting it just for more information) :
<?php
require_once('connection.php');
if($_REQUEST['movie_name']){
$name = $_REQUEST['movie_name'];
$year = $_REQUEST['movie_year'];
$genre = $_REQUEST['movie_genre'];
$sql = "INSERT INTO movies(name, year, genre) VALUES ('$name','$year','$genre')";
$query = mysqli_query($conn, $sql);
}
?>
Here's delete_row.php file for deleting entry with delete button:
<?php
require_once('connection.php');
$id = $_REQUEST['id'];
if(isset($_REQUEST['delete'])){
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
As you can probably see I was all over the place with php and ajax because I tried to implement multiple solutions or mix them to solve the problem.
At this stage when I click delete button I get alert message that says erasing is successful and adminpanel.php reloads with list of movies. However the movie is still there and in SQL database.
When I tried to debug delete_row.php I found out that index "id" is undefined every time even though I think I'm passing it with ajax call.
Edit
I should've said that security is not my concern right now, I do this exercise just for functionalities I described. :) Security is my next step, I am aware this code is not secure at all.

When I tried to debug delete_row.php I found out that index "id" is
undefined every time even though I think I'm passing it with ajax
call.
The reason this happens is probably because you're accessing delete_row.php directly through the browser, and because the form is not submitted (it will later through ajax) the $_REQUEST variable will always be undefined.
When debugging $_REQUEST (or $_POST) variables in the future, you should use Postman where you can actually request that php file sending your own POST arguments.
On your specific code, the query will never run because of this line:
if(isset($_REQUEST['delete']))
Which is checking for a delete variable that was never sent in the first place, hence will always resolve false
Use this code instead on delete_row.php:
<?php
require_once('connection.php');
if(isset($_REQUEST['id'])){
$id = $_REQUEST['id'];
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>

Related

Is there a way to pass value of a Button on click to another php file?

My aim is to get the lec_id which is the Button value when the button is clicked and pass it to chapters.php where I use the button value for a SQL query.
Below is part of my code for index.php
<?php
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from lectures";
$result = mysqli_query($con, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lec_id = $row['lec_id'];
$lec_name = $row['lec_name'];
$lec_number = $row['lec_number'];
$lec_views = $row['lec_views'];
echo "<button id=linkButton name={$row['lec_name']} value={$row['lec_id']} type='button' class='btn btn-outline-primary lecture' onclick='buttonClicked(this)'>
{$row['lec_name']}
</button> ";
}
} else {
echo "0 results";
}
?>
my button onclick function
function buttonClicked(btn) {
btn.click_counter = (btn.click_counter || 0) + 1;
document.getElementById("num_clicks_feedback").textContent = `btn ${btn.getAttribute('name')} has been clicked ${btn.click_counter} times`;
localStorage.setItem("lecId", btn.getAttribute('value'));
location.href = 'index.php?action=lec_hub/chapters';
}
I want to use the Button value here in chapters.php for a SQL query.
<html>
<head></head>
<body>
<?php
echo "<p id='lecId'></p>";
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from chapters where <<this is where i want to use lecId>> ";
?>
<script>
function getValue(){
var lecId = localStorage.getItem("lecId");
document.getElementById("lecId").innerHTML = lecId;
var resetValue= 0;
localStorage.setItem("lecId", resetValue)
}
getValue()
</script>
</body>
</html>
Welcome to Stack Overflow! As Barmar stated in their comment, you can pass data to a PHP file using URL parameters, or more commonly known as GET parameters. Here's how you do it.
From your file with your button in it, you can create a form like this one:
<form action="chapters.php" method="get">
<input type="text" name="data" /> <!-- This is the value that will be passed -->
<input type="submit" value="Button" /> <!-- This is your button -->
</form>
And then from your PHP file, you can get that passed data like this:
echo $_GET["data"]
$_GET is a global PHP array that contains all of the URL parameters sent to the file. you can pass multiple values as GET parameters to a file. You can read all about the $_GET variable here. I hope this helps!

Passing a PHP variable with fetched data to a JavaScript variable returns NULL or empty

I have an issue with returning the value of a PHP variable in JS. It returns NULL or empty instead of returning the age.
Approach:
Passing PHP variable with data to a JS variable in a separate file. Display JS variable in an alert(). Data was fetched from the database using fetch_assoc() in a while loop. Without using Ajax!
Proposed plan:
Enter a name.
Submit.
PHP fetches the age associated with that name.
age is stored in a PHP variable dbage.
Passed into JS variable to alert user what their age is.
I am trying to pass $dbage from sampletest.php to user in sample.php which will onsubmit display an alert saying: "Your age is blah".
blah is $dbage, which contains the age. This is for testing. Once I understand why this isn't working, I can move on to sending these JS variables to functions that will do calculations and return back to the DB.
What I have tried so far..
Trying to catch echo using ob_start() but that returned NULL as well.
Example:
ob_start();
echo $dbage;
$output = ob_get_contents();
ob_end_clean();
Making $dbage a global variable. Returns empty.
Echo variable outside the while loop but that returned NULL.
Example:
$dbage = '';
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
echo $dbage;
Any suggestions, corrections are appreciated.
sample.php (index file)
<?php
include 'sampletest.php';
session_start();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<div id="id03">
<form class="modal-content" action="sampletest.php" method="post" onsubmit="myFunction()">
<div class="container">
<input type="text" id="name" placeholder="Enter name" name="name">
<div class="clearfix">
<button type="submit" class="loggedinbtn" name="load"/>Load
</div>
</div>
</form>
</div>
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
</body>
</html>
sampletest.php
if(isset($_POST['load'])){
require 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
if(empty($name)) {
echo "Enter a number";
}elseif(!preg_match('/^[a-z ]+$/i', $name)){
echo "Enter a letter, no numbers";
}else{
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("location: sample.php?Connect-database=failed");
exit();
}
$sql = "SELECT name, age FROM results WHERE name= '$name';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
}
else{
echo "0 results";
}
$conn->close();
}
}
your action in the form should be set to sample.php, i think is the first problem. then get rid of the javascript all together.
<form class="modal-content" action="sample.php" method="post">
then change:
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
to just
<script>
var user = <?php echo $dbage; ?>;
alert("This is a php varible " + user);
</script>
submitting html forms to PHP does not require javascript at all.
From what I can see is that the actual query that you're sending is { name= '$name' }, try { name=' " . $name . " ' }.

actual code for xferring javascript variable to post variable

I have looked at this site for three days. I admit I am new to using javascript. But I have used the many different solutions offered and none have worked. Please help.
I am trying to do something that should be simple: save a user choice of country from a dropdown box on an html5 page to a hidden post variable (using javascript onchange.) That is used in a post array on the same form for a php operation that sends the input to a mysql database. This is my code:
The hidden post variable doesn't update. From there I can't test the code logic. But my onchange code came from this site and is suppose to work.
References:
<script type="text/javascript" src="../../js/jquery-2.1.4.min_prod.js"> </script>
<script type="text/javascript" src="../../js/respond.min.js"> </script>
<script type="text/javascript" src="../../js/bootstrap.min.js"> </script>
form information:
<form name="form1" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" />
</form>
form element
$query="SELECT * from country ";
$query=$query."ORDER BY country asc";
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select id="country" onchange="send_name(this)">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);
?>
<input type="hidden" id="c_php_value" name="c_php_value" value="">
Javascript
function send_name(selectObjectI) {
var value = selectObjectI.value;
$.ajax({
type: "POST",
url: "http://localhost/php/protected/form_addnews.php",
data:{c_php_value: value}
});
Post Submit Code
$country_id1 = trim($_POST['c_php_value']);
Thanks to a coder on utube, speaking german I might add, I discovered I don't need javascript, ajax or anything complicated to accomplish what I am trying to do.
I simply needed to do the following:
(1) Add a name="" to the dynamically created SELECT flag(name="country_id2").
(2) user chooses input with drop down box created.
(3) gather the $_POST after the form submit is set.
($country_id = $_POST['country_id2'])
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select name="country_id2" id="country_id2">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);

how to pass data from one html page to second in php?

I have created a page for updation of record. I want to pass the id of student from one page to another. I am trying to send it through window.location but it is not working. In ajax I tried to navigate to other page but didn't succeed in that too. How can i pass the data and receive on other page without showing in query string?
ajax code is
var id = $(this).data('username');
$.ajax({
var id = $(this).data('username');
$.ajax({type: "POST",
cache: false,
data: id,
url: "Update.php",
success: function(dto)
{
//but I do not require this return call I just
// want to pass the data to update.php
}
});
//this is the code where the button is being clicked
<table class="table table-condensed" >
<thead style="background-color:#665851" align="center">
`<tr>
<td style="color:white">Roll No</td>
<td style="color:white">Name</td>
<td style="color:white">Department</td>
<td style="color:white">Click To Update</td>
</tr>
</thead>
<tbody style="background-color:whitesmoke; border:initial" id="tblBody" align="center">
<?php
$database="firstdatabase"; //database name
$con = mysqli_connect("localhost","root" ,"");//for wamp 3rd field is balnk
if (!$con)
{ die('Could not connect: ' . mysql_error());
}
mysqli_select_db($con,$database );
$state = "SELECT rollno ,name, dept FROM student ;";
$result = mysqli_query($con,$state);
$output = 1;
$outputDisplay = "";
$noRows = mysqli_affected_rows($result);
if($result)
{
$num = mysqli_affected_rows($con);
//$row = mysqli_fetch_array($result,MYSQLI_NUM);
while ($row = mysqli_fetch_array($result))
{
$r = $row['rollno'];
$n = $row['name'];
$d = $row['dept'];
$outputDisplay .= "<tr><td>".$r."</td><td>".$n."</td><td>".$d."</td><td align='right'>
<button type='button' name='theButton' value='Detail' class='btn' id='theButton' data-username='$r'> <img src='edit.jpg'/></button>
</td>
</tr>";
}
}
else
{
$outputDisplay .= "<br /><font color =red> MYSql Error No: ".mysqli_errno();
$outputDisplay .= "<br /> My SQl Error: ".mysqli_error();
}
?>
<?php
print $outputDisplay;
?>
</tbody>
</table>
If both pages are at same domain you can use localStorage, storage event to pass data between html documents
At second page
window.addEventListener("storage", function(e) {
// do stuff at `storage` event
var id = localStorage.getItem("id");
});
at first page
// do stuff, set `localStorage.id`
localStorage.setItem("id", "abc");
When you use window.location then your page go to another page. ajax work on active page. You can not use.
Generally you can use sessions for this $_SESSION variable to store it into the session, or you can pass that value via get parameter. And afterwards get that parameter with $_GET
Or $_POST parameter if you want to submit form.
you can try using cookies
Set the cookie
<?php
setcookie("name","value",time()+$int);
/*name is your cookie's name
value is cookie's value
$int is time of cookie expires*/
?>
Get the coockie
<?php
echo $_COOKIE["your cookie name"];
?>
Populate a <form method="post" [...]> in the first page with the information needed; you can change their aspect with CSS as desired.
When the <form> is send you only need a PHP script/page that uses $_POST to fill the new page.
Easier than AJAX if you try to navigate from the first page to the second.
If you already have a form and wanna post that to an update script, you could just add the student id as an hidden form element example:
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
Else if you want to redirect from another page to the update page, with a student id, the best way will probably be a $_GET variable.
So the URL would look something like this: http://domain.com/update.php?student_id=1
And then your update.php will include a simple check like this.
if(!empty($_GET['student_id'])) {
$student_id = $_GET['student_id'];
// Ready to update
} else {
// Throw 404 error, or redirect to an create page
}

asynchronous commenting using ajax

I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.

Categories