Adding and deleting a row from SQL database using Ajax and JQuery - javascript

I have a PHP snippet that generates a table and fills it, and adds a delete button at the end of each row.
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><form action='delete.php' method='post'><button type='submit' value=$num name='deleteId'>delete</button></form></td>";
echo "</tr>";
}
The delete.php file is this one :
<?php
$host="localhost";
$username="root";
$password="";
$db_name="students";
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$id = $_POST['deleteId'];
$sql="DELETE FROM students WHERE id='$id'";
$result=mysql_query($sql);
?>
I want to do this using Ajax asynchronously, ie. I don't want my page to refresh. Tried a million ways, yet it fails each time. Thanks in advance.

Instead of using a form, you need to write your own JavaScript to handle the server call. Here's one way to do it. Make your PHP look something like this:
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button onclick="deleteStudent($num)">delete</button></td>";
echo "</tr>";
}
And then have a JS function that looks something like this:
function deleteStudent(studentId) {
$.ajax({
url: "delete.php",
method: 'post',
data: {
deleteId: studentId
}
});
}

Another way:
Firstly, assign a unique ID for each of the delete button.
while($row = mysql_fetch_array($result)){
$num = $row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button id='delete-" . $row['id'] . "'>delete</button></td>";
echo "</tr>";
}
Then use jQuery:
$('button[id^="delete"]').click(function () {
var id = $(this).attr('id').substr(6);
$.ajax({
type: "POST",
url: "delete.php",
data: {deleteId: id}
});
});

Related

Using JS element in PHP

I've a button inside a form:
echo '<tr class="user-personal-info">';
echo "<td><p>".$row['user_id']."</p></td>";
echo "<td><input placeholder='Username' type='text' value='".$row['user_name']."'/></td>";
echo "<td><input placeholder='Email' type='email' value='".$row['user_email']."'/></td>";
if($row['user_status'] == 1) {
echo "<td><select>";
echo "<option>User</option>";
echo "<option>Admin</option>";
echo "</select></td>";
} else {
echo "<td><select>";
echo "<option>Admin</option>";
echo "<option>User</option>";
echo "</select></td>";
}
echo "<td><input id='delete_btn' onclick='deleteUser(this);' type='submit' value='Delete'/></td>";
echo '</tr>';
As you can see there is a click event on the button. When i hit the button the following javascript function is executed. ID containes the id of a specific row ($row['user_id']):
function deleteUser(deze) {
const ID = deze.parentNode.parentNode.children[0].innerText
$.ajax({
url: "./includes/delete_user.php",
method: "POST",
data: {id:ID},
success: function(data) {
alert(data);
}
});
}
I want to send this ID variable to PHP to delete that specific record that matches with the ID. The problem is that my ID from JS is not send to PHP. When i echo this in PHP i get following error: Notice: Undefined index: id in....
PHP code:
<?php
include_once('./conn.php');
session_start();
$id = $_POST['id'];
echo $id; //can't echo this variable sent from javascript...
?>
You've put your submit button in a <form>, so after the JavaScript runs (but before the Ajax response is back and you alert it) the browser navigates to a new page (killing the JS program that is waiting for the response).
It is the new page that is showing the error and not the Ajax response.
Don't use type="submit" if you don't want to submit a form.
Use type="button".

How Do I Edit a Single Row?

So I am currently working on a forum, and I want to be able to have users edit their own questions and replies. Currently I am able to edit questions (sort of *other error is below) just fine. But replies are my biggest problem right now. Currently it shows an edit button under a reply but then it will allow me to edit ALL the other replies on the page and then when I save it, it saves the very last row.
<h3>Replies:</h3>
<div id="replies">
<?php
while($rows = mysqli_fetch_array($result2)) {
?>
<p id="dates"><?php echo $rows['a_datetime']; ?></p>
<div id="reply">
<b><p><?php echo $rows['a_username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['a_answer']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', '<p id="reply'.$rows['a_id'].'">'.$text.'</p>');
} else {
?>
<p id="reply<?php echo $rows['a_id']; ?>"><?php echo htmlspecialchars($rows['a_answer']); ?></p>
<?php
}
if($_SESSION['username'] == $rows['a_username']) {
$editReply = true;
?>
<div id="questionId"><?php echo $rows['question_id'];?></div>
<div id="replyId"><?php echo $rows['a_id'];?></div>
<button id="editReply">Edit</button>
<button id="saveReply">Save</button>
<button id="cancelReply">Cancel</button>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#saveReply').hide();
$('#cancelReply').hide();
});
</script>
<?php
}
?>
</div>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#editReply').click(function() {
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','true');
$('#reply<?php echo $rows['a_id']; ?>').css('background','white');
$('#reply<?php echo $rows['a_id']; ?>').css('border','solid 1px');
$('#saveReply').show();
$('#cancelReply').show();
$('#editReply').hide();
});
$('#saveReply').click(function() {
// Get edit field value
$detail = $('#reply<?php echo $rows['a_id']; ?>').html();
$q_id = $('#questionId').html();
$a_id = $('#replyId').html();
$.ajax({
url: 'editReply.php',
type: 'post',
data: {detail: $detail, q_id: $q_id, a_id: $a_id},
datatype: 'html',
});
$('#editReply').show();
$('#saveReply').hide();
$('#cancelReply').hide();
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','false');
$('#reply<?php echo $rows['a_id']; ?>').css('background','#D8D8D8');
$('#reply<?php echo $rows['a_id']; ?>').css('border','none');
});
$('#cancelReply').click(function() {
$('#editReply').show();
$('#saveReply').hide();
$('#cancelReply').hide();
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','false');
$('#reply<?php echo $rows['a_id']; ?>').css('background','#D8D8D8');
$('#reply<?php echo $rows['a_id']; ?>').css('border','none');
});
});
</script>
<?php
}
?>
editreply.php:
<?php
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = ""; // Mysql password
$db_name = "db"; // Database name
$tbl_name = "fanswer"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
$detail = htmlspecialchars($_POST['detail']);
$q_id = $_POST['q_id'];
$a_id = $_POST['a_id'];
// Add your validation and save data to database
echo $detail;
echo $q_id;
echo $a_id;
$sql = "UPDATE $tbl_name SET a_answer = '$detail' WHERE question_id='$q_id' AND a_id= '$a_id'";
$result = mysqli_query($conn, $sql);
?>
Originally I had all the editable content in divs but for some reason it made some pages load funny so for now I was hoping to use the p tag.
How can I make it so only one of the replies are editable and so it only sends that information to the editreply.php script?
*My other problem which is sort of a side problem, when I go to edit something that has a link in it I get a load of gibberish posted into my database. E.g. a user post LMAO: https://afunnypic.com, the information in my database says:
LMAO: <a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="https://afunnypic.com" rel="nofollow">https://afunnypic.com</a><br>
Which I don't understand.
Just found my answer to the first problem, all I did was move the script inside the if ($editReply = true) statement and it worked!
If anyone can help with the second bit on editing the links bit that would be great!

PHP: javascript alert, with value from sql query, into IF condition

With the following code, a popup table should appear with sql query data, only when retrieved records are greater than 1.
$sql = "SELECT * FROM pt_locations WHERE country = ('$countryCode') AND location = ('$cityCode')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount . "<br /><br />";
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert' .$message;
foreach($result as $val){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
echo '</script>';
}
Recording counts are done correctly, but I can not make the popup appear in any way.
try this. Hope this help you.
$sql = "SELECT * FROM pt_locations WHERE country = ('country') AND
location = ('location')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount;
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert("'.$message.'")';
echo '</script>';
while($val=mysqli_fetch_assoc($result)){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
}
There are some errors, because for logic you must put the alert at the end of the table complete, just for logic and after you put alert something without brakets and you open a script before the foreach loop and after the foreach loop you close the script, this is absolutley wrong, another error is in the $message, you are using br inside an alert javascript that isn't recognize as html but just like characters at the least you can use unicode \n\t not br, i used also a setTimeout,but works also without setTimeout.
Sometimes can result essential use javascript injection inside the php for example to autofill of some forms and input select or to call a change event from external compilation of other application that pass variables in get and need to autofill a form, but i think in this case is not necessary do a javascript injection you can print the total Records just in the page, btw...
The code under works
Bye
$message = "Records found: " . $rowcount." \\n\t\\n\t";
if ($rowcount > 1) {
foreach($result as $val){
//var_dump($val);
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
$jvsVar = "<script type='text/javascript'>;setTimeout(function(){alert('$message');},100)</script>";
echo $jvsVar;
}

Displaying JSON data created using PHP and MySQL

I have a form on an HTML page which posts a user input to a PHP which executes a SQL statement to get information from a database and output it in JSON. Here is my PHP code to get the JSON data:
<?php
header('Content-type:application/json');
$con = mysqli_connect('localhost','root','','dbname');
if(isset($_POST['submit']))
{
$artist = $_POST['artist'];
$select = mysqli_query($con, "SELECT * FROM tblname WHERE artistName = ". $artist);
$rows = array();
while($row = mysqli_fetch_array($select))
{
$rows[] = $row;
}
echo json_encode($rows);
};
?>
When I submit the form on the HTML page, it goes to the PHP page and I get this result:
[{"0":"6","id":"6","1":"OASIS","artistName":"OASIS","2":"SOME MIGHT SAY","songTitle":"SOME MIGHT SAY","3":"1995-05-06","dateNo1":"1995-05-06"}]
(Code and JSON result have been simplified for this question)
Instead of going to this page, I'd like the data to be displayed nicely on the HTML page so that a user does not see this array. I'm not sure how to do this, any help?
Thank you!
If you want the output formatted nicely, why are you encoding in JSON? JSON, although human-readable, isn't intended to be rendered on-screen as an end product.
I'd recommend looping through the $rows array and building a simple HTML table. You could, of course, wrap the data in any markup you like and even add CSS to style it as you see fit. Here's an example to get you started:
echo "<table>";
foreach($rows as $row) {
foreach($row as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
If you only want some of the data rendered, you can simply echo those values:
foreach($rows as $row) {
{
echo "Artist:" . $row['artistName'];
echo "<br>";
echo "Song Title:" . $row['songTitle'];
echo "<br>";
echo "Date:" . $row['dateNo1'];
}
There are two ways to solve this problem :
Perform AJAX call from Javascript to PHP Page and parse the success response in to the HTML.
Simply echo the values in PHP Page or add HTML itself in PHP Page as suggested by Tim.

Validate PHP variable via Javascript

Im looking to pass one variable from my PHP code to my Javascript code to validate a figure. I'm creating a shopping cart scenario whereby i have a variable 'in_stock' which specifies the amount of stock available for a product. If I enter an amount that is greater than the 'in_stock' available i need an error to be thrown. This is currently what I have:
Java Script
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable ="<?php echo $stock?>";
//To check if a non-numerical value is entered
if (isNaN(enteredChar))
{
alert("Not a Number!");
return false;
}
//To check if the input is empty
if (enteredChar=="")
{
alert("Empty!");
return false;
}
//To check if the amount entered is not greater than the amount in stock
if (enteredChar > stockavailable)
{
alert("Not enough in stock");
return false;
}
}
</script>
This is all occurring whilst my PHP has called the database and returned the value on the screen. As follows:
PHP
$product_id =(int)$_GET['product_id'];
$username = "potiro";
$password = "pcXZb(kL";
$hostname = "rerun";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("poti",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM products where product_id=$product_id");
echo '<form name="form1">';
echo '<table class="Grocery-table">';
while($row = mysql_fetch_array($result))
{
$stock =$row['in_stock'];
$product_id = $row['product_id'];
echo "<tr><td><b>Product ID</b></td>";
echo "<td>";
echo $product_id;
echo "</td></tr>";
echo "<tr><td><b>Product Name</b></td>";
echo "<td>";
echo $row['product_name'];
echo "</td></tr>";
echo "<tr><td><b>Unit Price</b></td>";
echo "<td>";
echo $stock;
echo "</td></tr>";
echo "<tr><td><b>Unit Quantity</b></td>";
echo "<td>";
echo $row['unit_quantity'];
echo "</td></tr>";
echo "<tr><td><b>In Stock</b></td>";
echo "<td>";
echo $row['in_stock'];
echo "</td></tr>";
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
}
echo "</table>";
echo "</form>";
mysql_close($dbhandle);
?>
add your stock value to a hidden input value stock_value
echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart" ></input><Input type="hidden" id="stock_value" name="stock_value" value="'.trim($stock).'"></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
in javascript
<script language="javascript">
function numCheck()
{
var enteredChar = document.getElementById('add_value').value;
var stockavailable =document.getElementById('stock_value').value;

Categories