delete sql row after echo onClick - javascript

I am making a program for a quiz show in our school programme. I have a table that contains WHO asked the question (among the teachers), WHAT is the question and another table as to what the answer to that question is. So, I have a table with THREE COLUMNS.
Now, what I was trying to do is that when the page loads, it will display a number of links labeled . I echoed each link such that when you click any of them, a random row will be taken from MySQL table and the "Question" as well as who asked that particular question will be displayed publicly.
so far, i was able to do all that just fine. But here's the problem.
I want to do it in such a way that after clicking the question, (after displaying it, to be exact,) that specific row will be DELETED from the MySQL table. I didn't want to use a timer because the time allotted for each question differs. I was wondering if there is some kind of "after click" function (or some way to do it) in javascript and AJAX. or perhaps a PHP code?
sorry for the noobish question. History teacher here. :)
by the way, here is a part of my code:
<?php
$checkrow = $db->query("SELECT * FROM questions WHERE `who` = $teachers");
while ($row = $checkrow->fetch(PDO::FETCH_ASSOC))
{
$who = $row['who'];
$question = $row['question'];
$date =$row['date_asked'];
$ask = $db->query("SELECT COUNT(*) FROM teachers WHERE science = $from AND who = $teachers");
$count = $ask->fetch(PDO::FETCH_NUM);
if($count[0] == 0) {
echo ' MYSTERY QUESTION ';
$fromwho = "From science Department.";
echo "<br>";
} else {
echo ' MYSTERY QUESTION ';
$fromwho = "From your Arts Department.";
echo "<br>";
}
}
?>
and here is my javascript.
<script language="javascript">
function readmsg(){
var qst = "<?php echo $question; ?>";
var dte = "<?php echo $date; ?>";
var frm = "<?php echo $fromwho; ?>";
document.getElementById("displaymsg1").textContent = qst;
document.getElementById("displaymsg2").textContent = dte;
document.getElementById("displaymsg3").textContent = frm;
}
</script>

1st, you have to make page delete_question.php (or method like this):
<?php
$db->query(('DELETE FROM questions WHERE ID=' . $_GET['uid']); // make it safer
echo '{result:"done"}';
?>
2nd, make delete onclick handler function with ajax sends UID to specified
function delete_question(el) {
$.ajax({
url : 'delete_question.php',
dataType : 'json',
data : {
uid : el.dataset.uid
},
success : function(response) {
// remove line?
$(el).parent().remove();
alert(response.result);
}
});
3nd: add handler to element
<a href="#" onclick="delete_question(this)" data-uid="<?php echo $row['ID'] ?>">

Related

change div backgroundcolor with js and php

i am working on my first own website. i try to display which cinema seats are already booked, by turning theire backgroundcolor red. i store the reservations in an sql database. i do get the correct value and i can display it on my website, but still the getById won t work.
This is how i create the divs i want to tune:
<?php
for ($i=0; $i < $saalinfo[2]; $i++) {
echo "<div class='rowsaal'>";
for ($j=0; $j < $saalinfo[3]; $j++) {
$k = $i+1;
echo "<a onclick='JavaScript:removeday($k$j)';>";
echo "<div id='$k$j' class='seat' >";
echo "</div>";
echo "</a>";
}
echo "</div>";
}
?>
This is the way i try to change the background color. I used the exact same js wording in other occasions and it did work so i am guessing my id value is not right:
function getres(){
var date = document.getElementById('labeldate').value;
document.getElementById('showdate').innerHTML = date;
var booked;
booked = "<?php echo $dis; ?>"; //$dis is one value i get back from mysqli_fetch_array in this case its 34
document.getElementById(booked).backgroundColor = "red";
document.getElementById('showdate').innerHTML = document.getElementById('showdate').innerHTML + booked;
}
For clarification: booked shows the correct value which is 34 in this case. In the database itself its saved as a txt value. if i look into the html source code i can see that the value 34 is assigned for booked.
booked = "34";
but the div id is set in the following pattern as it is limitted in the use of '' because they are formed in php
</a><a onclick='JavaScript:removeday(34)';><div id='34' class='seat' ></div></a>
i already had some issues where the use of "" and '' lead to different results. Is this the same case here? and how can i fix the issue? Many thanks in advance.
I have not checked all of your code but there is no "backgroundColor" on the element. You need the style property.
document.getElementById(booked).backgroundColor = "red";
should be
document.getElementById(booked).style.backgroundColor = "red";

How to use javascript if statements within function to populate table

I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}

Trying to delete an entry in a table. Query doesn't delete the row, no idea how to debug

I'm trying to delete an entry in my database using the code below. The javascript function takes me to index.php?delpost= with the correct "adventureID" but when I check my database the row is still there. I've very recently started using PDO so I'm wondering if the execute() statement might be the issue. $dbh connect to my database at the top of the page and it is working as it prints every row from the table I'm trying to delete rows from. My goal is to successfully delete a row when I call the javascript function. The issue is - it doesn't.
<script language="JavaScript" type="text/javascript">
function delpost(adventureID, title)
{
if (confirm("Are you sure you want to delete '" + title + "'" + " '" + adventureID + "'"))
{
window.location.href = 'index.php?delpost=' + adventureID;
}
}
</script>
<?php
if(isset($_GET['delpost'])){
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
header('Location: index.php?action=deleted');
exit;
}
?>
<?php
if(isset($_GET['action'])){
echo '<h3>Post '.$_GET['action'].'.</h3>';
}
try {
foreach($dbh->query("SELECT adventureID, title, postDate FROM adventure ORDER BY adventureID DESC") as $row) {
echo '<tr>';
echo '<td>'.$row['title'].'</td>';
echo '<td>'.date('jS M Y', strtotime($row['postDate'])).'</td>';
?>
<td>
Delete
</td>
<?php
echo '</tr>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Probably you are facing problem with MYSQL SAFE UPDATES being ON. To avoid it and be able to finally delete rows, you can engage in the following tactics:
SET SQL_SAFE_UPDATES = 0;
--- YOUR DELETE STATEMENT ---
SET SQL_SAFE_UPDATES = 1;
To check if you have SQL_SAFE_UPDATES enabled you can do by running:
SHOW VARIABLES LIKE 'sql_safe_updates'
Try to replace this code :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
By the following :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->bindParam('adventureID', $_GET['delpost']);
$stmt->execute();
Explanation :
You can either : Use ":variable" in your query, then pass variables by binding them with the "bindParam" function.
Or : Use "?" in your query, and then pass variables in the "execute" function.
Full example can be found here : http://php.net/manual/fr/pdostatement.execute.php#example-1050

Executing javascript in an an AJAX response - Codeigniter

I am using Codigniter to redo a website. I have the following controller code:
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
foreach ($topics as $val) {
echo "<pre id = \"pre_" . $val['id'] . "\">";
echo $val['formula'];
echo "<br />";
// generate a unique javascript file.
$f = "file_" . $val['id'] . ".js";
if (!file_exists($f));
{
$file = fopen($f,"w");
$js = "\$(\"#button_" . $val['id'] . "\").click(function(){\$(\"#pre_" . $val['id'] . "\").hide();});";
fwrite($file,$js);
fclose($file);
}
echo "<script src=\"file_" . $val['id'] . ".js\"></script>";
echo "<button id=\"button_" . $val['id'] . "\">Hide</button>";
echo "</pre>";
}
}
The basic idea to make an AJAX call to the function to retrieve a list of formulas.
The purpose of the javascript is to be able to hide any of the formulas by
hiding the <pre> </pre> tag that surrounds them The js file (i.e. file_1.js) I generate looks like:
$("#button_1").click(function(){$("#pre_1").hide();});
and the button code is:
<button id="button_1">Hide</button>
The problem is that it doesn't work. The files get generated, but clicking on the "Hide"
button does nothing. The puzzling part is that the exact same code works on the original website where I just make an AJAX call to a PHP file that generates the same code.
Any ideas what could be going on here?
Edit:
On my old website I used:
$query = "SELECT * FROM topics WHERE term LIKE '%" . $term . "%'";
$result = mysql_query($query);
while ($val = mysql_fetch_array($result))
{
echo "<pre id = \"pre_" . $val['id'] . "\">";
etc.
etc.
}
and everything works fine. If I now put the results of the while loop into to an array and then do a foreach loop on that, the results are very intermittent. I'm wondering if the foreach loop is the problem.
i think you can return list buttons in json response
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
$response = array('buttons' => $topics);
header('Content-Type: application/json');
echo json_encode( $arr );
}
so client can parse which button element to be hide.
<script type="text/javascript">
$(document).ready(function(){
$('somEL').on('submit', function() { // This event fires when a somEl loaded
$.ajax({
url: 'url to getTopics() controller',
type : "POST",
data: 'input_data=' + $(this).val(), // change this based on your input name
dataType: 'json', // Choosing a JSON datatype
success: function(data)
{
for (var btn in data.buttons) {
$(btn).hide();
}
}
});
return false; // prevent page from refreshing
});
});
</script>

AJAX to call PHP file which removes a row from database?

Alright, so I asked a question yesterday regarding how to save the blog posts that a user makes. I figured out the database side of it, and that works fine. Now, I want to REMOVE a blog post based after clicking an onclick button. Through my hours of digging through the web, I've found calling an jQuery AJAX function is the best way to go about it. I've been tooling around with it, but I can't get this working.
Blog code retrieved from database in blog.php:
$connection = mysql_connect("...", "...", "...") or die(mysql_error());
$database = mysql_select_db("...") or die(mysql_error());
$query = mysql_query("SELECT * FROM template") or die(mysql_error());
$template = mysql_fetch_array($query);
$loop = mysql_query("SELECT * FROM content ORDER BY content_id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($loop))
{
print $template['Title_Open'];
print $row['title'];
print '<button class="deletePost" onClick="deleteRow(' . $row['content_id'] . ')">Remove Post</button>';
print $template['Title_Close'];
print $template['Body_Open'];
print $row['body'];
print $template['Body_Close'];
}
mysqli_close($connection);
This creates the following HTML on home.php:
<div class="blogtitle" class="post3">Title
<button class="deletePost" onClick="deleteRow(3)">Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
Which should call my remove.js when button is clicked (This is where I start to lose what I'm doing):
$function deleteRow(id){
$.ajax({
url: "remove.php",
type: "POST",
data: {action: id}
});
return false;
};
Calling remove.php (No idea what I'm doing):
$con=mysqli_connect("...","...","...","...");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['action'];
$query = mysql_query("DELETE FROM content WHERE content_id=$id") or die(mysql_error());
My goal here is to REMOVE the row with the ID from the table which would in turn remove the blog post entirely since it won't see the row when it loops through the database table.
Any ideas?
Thanks for your help,
Kyle
couple of issues in your original code: the functions in Jquery shouldn't use a $ sign at the beginning and since you need to pass a single value I would use the query string rather than the POst, and instead of calling the "die" in php I would use the affected rows to return the callback of whether or not the value was deleted. But this is just my approach, there other ways I'm sure.
Here are little improvements in you code:
//HTML
<div class="blogtitle" class="post3">Title
<button class="deletePost" data-item="3" >Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
//JQUERY
jQuery(document).ready(function($) {
$('button.deletePost').each(function(){
var $this = $(this);
$this.click(function(){
var deleteItem = $this.attr('data-item');
$.ajax({url:'remove.php?action='+deleteItem}).done(function(data){
//colect data from response or custom code when success
});
return false;
});
});
});
//PHP
<?php
$id = $_REQUEST['action'];
$query = mysql_query('DELETE FROM content WHERE content_id="'.$id.'"');
$confirm = mysql_affected_rows() > 0 ? echo 'deleted' : echo 'not found or error';
?>
Hope this sample helps :) happy coding !
i hope this should help you i used this to remove items from my shopping cart project.
$(".deleteitem").each(function(e) {
$(this).click(function(e) {
$.post("library/deletefromcart.php",{pid:$(this).attr('prodid'), ajax:true},function(){
window.location.reload()
})
return false;
});
});

Categories

Resources