PHP & JavaScript - Confirm with values from drop down - javascript

I've got a form that I am populating from the database using PHP.
I would like a popup using Javascript confirming if the user would like to delete the movie.
The popup should contain the movie & release year.
Thus far, only the first value will appear in the popup...
print("<script type=\"text/javascript\">\n");
print("function confirmDelete(){");
print("var del = document.getElementById('movie').value;\n");
print("var status = confirm('Are you sure you wish to delete: ' + del + '?');\n");
print("return status;\n");
print("}</script>\n");
print("<h1>Delete Record</h1>");
//Select Movies
$query = "SELECT title release_year
FROM movies
ORDER BY title";
$result = mysql_query($query)
or die("<h1>Error - (Movies) the query could not be executed</h1>\n");
print("<form method=\"post\" action\"\">\n");
print("<select id=\"movie\" name=\"movies\">\n");
while ($row = mysql_fetch_array($result))
print("<option value=\"$row[0], $row[1]\">$row[0]</option>\n");
print("</select>\n");
print("<input name=\"select_delete\" type=\"submit\"
value=\"Delete\" onclick=\"return confirmDelete();\">\n");
print("</form>\n");
Whats the best way to tackle this?

Try this:
Javascript
var form = document.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
var x = confirm('confirmation message here');
if (x) {
form.removeEventListener('submit');
form.submit();
}
});

you can use this function to confirm user action
....
print("<input name=\"select_delete\" type=\"submit\"
value=\"Delete\" onclick=\"confirmDelete();\">\n");
print("</form>\n");
?>
<script>
function confirmDelete()
{
var e = document.getElementById("movie");
var msg = e.options[e.selectedIndex].value;
var x;
var r=confirm("Delete" + msg + "entry?");
if (r==true)
{
//OK button pressed
}
else
{
//Cancel button pressed
}
}
</script>

You can write the 'delete function' using ajax and most of your code you can simply write like this:
<?php
//code in php
?>
code in javascript
<?php
//more code in php
?>

Related

ajax response is showing javascript and not hidding it

I am building a comment system in which there is features like: delete main post, delete comment, delete reply, edit main post, edit comment, edit reply, Read more/Read less for post that is >250 character. So i am now at the stage of making the edit for reply post to a comment, everything else is working perfectly except this one, when i click i need to see reply post with Read More/Read Less feature, so to make this happen after ajax response i needed to paste the javascript codes for this feature in the php script which edit the reply, so when i make .html(data) i see the javascript codes inside the span which i want the response to be shown ! please help ! i made the same script for comment and same way placing javascript code in the php page that edited the comment but i do not see the javascript lines ! below are pictures that shows what is happening and my script next :
// THIS TAKES CARE OF THE EDIT FEATURE OF THE REPLY ON BOARD_COMMENT PAGE
$(document).on("click", ".board_reply_edit_button", function() {
// this will select the form in which is contained the edit button
var editBoardButtonAttribute = $(this).attr("id");
var editBoardButtonIdArray = editBoardButtonAttribute.split("-");
var editBoardButtonId = editBoardButtonIdArray[0];
$("#"+editBoardButtonId+"-formBoardReplyEdit").toggle();
$("#"+editBoardButtonId+"-spanBoardReplyEdit").toggle();
// if the cancel button is clicked, this happens
$(document).on("click", ".board_cancel_button", function() {
// this will select the form in which is contained the edit button
var cancelBoardAttribute = $(this).attr("id");
var cancelBoardButtonIdArray = cancelBoardAttribute.split("-");
var cancelBoardButtonId = cancelBoardButtonIdArray[0];
$("#"+cancelBoardButtonId+"-formBoardReplyEdit").hide();
$("#"+cancelBoardButtonId+"-spanBoardReplyEdit").show();
});
// if the edit button is clicked we send this ajax call
$(document).on("click", ".board_edit_save_button", function(e) {
e.preventDefault();
// this will select the form in which is contained the edit button
var saveBoardAttribute = $(this).attr("id");
var saveBoardButtonIdArray = saveBoardAttribute.split("-");
var saveBoardButtonId = saveBoardButtonIdArray[0];
var editBoardTextareaVal = $("#"+saveBoardButtonId+"-textareaBoardReplyEdit").val();
url = "widgets/edit_board_comment_reply.php";
if (editBoardTextareaVal === "") {
CustomSending("This post can't be left blank")
setTimeout(function () {
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
}, 2000);
// this makes the scroll feature comes back
setTimeout(function(){
$("body").css("overflow", "auto");
}, 2001);
} else {
$.ajax({
url: url,
method: "POST",
data: {
reply_id: saveBoardButtonId,
board_reply_textarea: editBoardTextareaVal
},
beforeSend: function() {
CustomSending("Sending...");
},
success: function(data){
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
// this makes the scroll feature comes back
$("body").css("overflow", "auto");
$("#"+saveBoardButtonId+"-spanBoardReplyEdit").html(data); //// THIS IS THE KEY LINE
$("#"+saveBoardButtonId+"-formBoardReplyEdit").hide();
$("#"+saveBoardButtonId+"-spanBoardReplyEdit").show();
}
});
}
});
});
this is the edit_board_comment_reply.php file :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
if(isset($_POST['reply_id'], $_POST['board_reply_textarea'])) {
$reply_id = (int)$_POST['reply_id'];
$board_reply_textarea = mysql_prep($_POST['board_reply_textarea']);
// INSERT into table
$query = "UPDATE board_comment_reply_table ";
$query .= "SET reply = '$board_reply_textarea' ";
$query .= "WHERE reply_id = $reply_id";
$result = mysqli_query($connection, $query);
// now we select the updated board post
$query2 = "SELECT * FROM board_comment_reply_table ";
$query2 .= "WHERE reply_id = $reply_id ";
$result2 = mysqli_query($connection, $query2);
confirm_query($result2);
$result_array = mysqli_fetch_assoc($result2);
}
echo nl2br($result_array['reply']);
?>
<script>
// This takes care of the board comment Continue Reading feature ---------------------------------------------------------
$(".reply_content_span").each(function(){
var boardReplyPostThis = $(this);
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
boardReplyPostThis.text(boardPostTextCut+"...");
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_more" id="'+boardPostId+'-readMoreComment">Read More</a>');
} else {
boardReplyPostThis.text(boardPostText);
}
$("body").on("click", ".board_reply_read_more", function(e){
e.preventDefault();
boardReplyPostThis.text(boardPostText);
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_less">Read Less</a>');
});
$("body").on("click", ".board_reply_read_less", function(e){
e.preventDefault();
boardReplyPostThis.text(boardPostTextCut+"...");
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_more">Read More</a>');
});
});
</script>
This is the html code :
<span class="comment_content_span" id="<?php echo $board_comment_id_number;?>-spanBoardCommentEdit"><?php echo nl2br($board_comment_text);?></span>
<form action="" method="post" class="board_comment_edit_form" id="<?php echo $board_comment_id_number;?>-formBoardCommentEdit">
<textarea rows="2" name="board_comment_edit_textarea" class="board_comment_edit_textarea" id="<?php echo $board_comment_id_number;?>-textareaBoardEdit"><?php echo $board_comment_text;?></textarea>
<input type="submit" value="Edit" class="board_edit_save_button" id="<?php echo $board_comment_id_number;?>-saveBoardCommentEdit"/>
<input type="button" value="Cancel" class="board_cancel_button" id="<?php echo $board_comment_id_number;?>-cancelBoardCommentEdit"/>
</form>
Solution found !
instead of the javascript between the script tags, I added this line in the edit_board_comment_reply.php
<script src="js/board.js"></script>
It seems that the appended javascript exitsts in "data" which is send back from your php script. First of all you should try to define the "dataType" property of your ajax-post because the output is preprocessed by jquery depending on that property.
After that you can try to grab just the content-division from your resonse-html and append that instead of the whole result.
For example like this $(body).append($(data).find('#contentID')).

how to call function if fetched data from database is != "Detained"

I fetched the data from my database and echoed it. Once I go to a prisoner's profile and his status is not = detained, the button 'Add Visitor' should be automatically disabled.
Where should I put my disable() function for it to be called?
Here's my script
<script language = "javascript" type = 'text/javascript'>
function disable(){
if(document.getElementById('prisonerstatus').value == "Detained"){
document.getElementById("visitorbtn").disabled= false;}
else{
document.getElementById("visitorbtn").disabled= true;
}
};
</script>
PHP
<?php
include "connect.php";
$idd =$_GET['id'];
$result = $connect->query("SELECT * FROM prisoner
INNER JOIN offensedata ON prisoner.prisoner_id = offensedata.prisoner_id
INNER JOIN arrestdata on prisoner.prisoner_id = arrestdata.prisoner_id
INNER JOIN booking ON prisoner.prisoner_id = booking.prisoner_id
WHERE prisoner.prisoner_id = $idd") or die($connect->error);
$rows1 = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows1 as $row){
$status = $row['status'];
echo "<input type = 'hidden' value = '$status' id = 'prisonerstatus'/>";
echo "<div class='col-lg-3'>Status: $status </div>";
}
Here's my button
<input type = "button" class="call_modal" style="cursor:pointer;margin-top:1%;" value = "Add Visitor" id = 'visitorbtn'>
Please excuse my code. This is for my school project only, these codes are what have been taught to us. I will study on how to avoid SQL injections and apply it soon. Thank you in advance :)

How to turn extracted href into hyperlink

I'm working on a tagging part on a site similar to Facebook. The idea is that whenever someone types # in the post area, a drop down menu appears containing all of his friends. He then picks who he wants to tag and clicks on that person's profile. I have a javascript function which detects when # is pressed, and then calls another js function which then in turn sends an ajax request to a php file for the list. And this part works great.
So when the user clicks on someone from their friend list, I set it up so that an href part containing the friend's username is extracted from the php file as plain text, and then displayed as a text string right after the # character in the post area (I prevented following to the profile after clicking with return: false). So, for example, when someone wants to choose John Smith, he presses #, the list appears, he picks John Smith, clicks on his profile, the list disappears, and then the username appears after #, like this: #john_smith
Now the trouble is that I would want to make john_smith after # into a hyperlink that would lead to John Smith's profile, instead of it being just plain text. And I've been really struggling to find a solution. Any help would be much appreciated.
Thanks a lot! :)
**//php ajax file**
<?php
$userLoggedIn = $_POST['userLoggedIn'];
$userLoggedIn = new User($con, $userLoggedIn);
$rez = array();
$rez = $userLoggedIn->getFriendArray();
if ($rez != ",") {
$no_commas = explode(",", $rez);
foreach ($no_commas as $key => $value) {
$friend = mysqli_query($con, "SELECT first_name, last_name, username, profile_pic FROM users WHERE username='$value'");
$row = mysqli_fetch_assoc($friend);
echo "<div class='displayTag'>
<a href=" . $row['username'] . " id='grabLink'>
<div>
<img src='" . $row['profile_pic'] . "'>
</div>
<div>
" . $row['first_name'] . " " . $row['last_name'] . "
<p style='margin: 0;'></p>
<p id='grey'></p>
</div>
</a>
</div>";
}
}
else {
echo "<br><p id='ynf'>You have no friends. Please add someone</p>";
}
**//js functions**
function userTag(user) { // for ajax
$.post("includes/handlers/ajax_user_tag.php", {userLoggedIn:user},
function(data){
$('.tag_results').html(data);
});
}
function textTag() { // for extracting href and placing # and username anywhere in the post area
$('.displayTag a').click(function(a){
var x = $(this).attr('href');
var y = $(this).prop('href');
var $txt = jQuery("#post_text");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
$txt.val(textAreaTxt.substring(0, caretPos) + x + textAreaTxt.substring(caretPos) );
$('.tag_results').html("");
return false;
});
}
**//js code**
$("#post_text").keydown(function (e) { // listens for #
if(e.which == 50)
userTag('<?php echo $userLoggedIn; ?>');
if(e.which != 50)
$('.tag_results').html("");
});
$('.tag_results').hover(function(e) { //calls textTag function on hover
textTag();
});
**//Empty div populated by ajax results**
<div class="tag_results">
</div>
EDIT:
I found out what the problem was, purely by accident. In the file with the php classes, strip_tags was used for all posts. So what I wanted to do was practically impossible with that turned on. Now it's working as it should. Thanks everyone for help! :)
I don't believe that your click event is capturing the click, because your php is dynamically creating the list element. Also your function, textTag() doesn't actually apply the event until that function is run, so it could be creating issues. Change your JS to -
$(document).on('click', '.displayTag a', function() {
var href = $(this).attr('href');
//other code applying href to new anchor tag in proper format
});
First I would change a little bit the PHP response in order to make it easier to get the firend's full name.
**//php ajax file**
<?php
$userLoggedIn = $_POST['userLoggedIn'];
$userLoggedIn = new User($con, $userLoggedIn);
$rez = array();
$rez = $userLoggedIn->getFriendArray();
if ($rez != ",") {
$no_commas = explode(",", $rez);
foreach ($no_commas as $key => $value) {
$friend = mysqli_query($con, "SELECT first_name, last_name, username, profile_pic FROM users WHERE username='$value'");
$row = mysqli_fetch_assoc($friend);
echo "<div class='displayTag'>
<a href=" . $row['username'] . " id='grabLink'>
<div>
<img src='" . $row['profile_pic'] . "'>
</div>
<div class='fullname'>
" . $row['first_name'] . " " . $row['last_name'] . "
<p style='margin: 0;'></p>
<p id='grey'></p>
</div>
</a>
</div>";
}
}
else {
echo "<br><p id='ynf'>You have no friends. Please add someone</p>";
}
Then I would modify the JS function
function textTag() { // for extracting href and placing # and username anywhere in the post area
$('.displayTag a').click(function(a){
var fullname = $(this).find('.fullname').text();
var x = ''+fullname +'';
var y = $(this).prop('href');
var $txt = jQuery("#post_text");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
$txt.html(textAreaTxt.substring(0, caretPos) + x + textAreaTxt.substring(caretPos) );
$('.tag_results').html("");
return false;
});
}

Confirmation Box doesnt show and automatically delete

HELP ME Please. I created a delete process wherein there i a confirm box to ask the user if he is sure or not.
but the confirm box doesnt appear and automatically deletes the data and doesnt even redirect me. Help me plss!
I need to show the confirmation box ("are u sure") and if the input is true. it will delete the data and redirect to other page.
<?php
require_once('connect/connect.php');
?>
<script>
var r = confirm("Are you sure?");
if (r == true)
{
alert(' item successfuly deleted!!');
</script>
<?php
if(isset($_GET['pid'])){
$sql ='Select * FROM product where pid = '.$_GET['pid'];
$qry = mysql_query($sql);
$data = mysql_fetch_array($qry);
$pname = $data['pname'];
$pstock = $data['pstock'];
}
$sq3="INSERT INTO report VALUES('NULL','".$pname."', '" .$pstock. "', 'Item Deleted' )";
$qry3 = mysql_query($sq3);
$sql2 = 'DELETE FROM product where pid = '.$_GET['pid'];
$qry2 = mysql_query($sql2);
?>
<script>
window.location.assign('products.php');
}
</script>
<script>
else
{
window.location.assign('products.php');
}
</script>
you missed the closing brace } of if condition
<script>
var r = confirm("Are you sure?");
if (r == true)
{
alert(' item successfuly deleted!!');
}
</script>
FIDDLE
Try a short if statement
(r == true) ? alert('item successfuly deleted!!') : "" ;
You have to remove the script tags before php tags start. Update the code as below:-
<?php
require_once('connect/connect.php');
?>
<script>
var r = confirm("Are you sure?");
if (r == true)
{
alert(' item successfuly deleted!!');
<?php
if(isset($_GET['pid'])){
$sql ='Select * FROM product where pid = '.$_GET['pid'];
$qry = mysql_query($sql);
$data = mysql_fetch_array($qry);
$pname = $data['pname'];
$pstock = $data['pstock'];
}
$sq3="INSERT INTO report VALUES('NULL','".$pname."', '" .$pstock. "','Item Deleted' )";
$qry3 = mysql_query($sq3);
$sql2 = 'DELETE FROM product where pid = '.$_GET['pid'];
$qry2 = mysql_query($sql2);
?>
window.location.assign('products.php');
}
else
{
window.location.assign('products.php');
}
</script>
Try this and confirm.

how to submit form and add a row in DB

I am having problem with this javascript function.
If I want to submit a form if I do this below it works:
function submitform()
{
var QandAO = document.getElementById("QandA");
QandAO.submit();
}
If I want to add a row into a DB table using AJAX to navigate to the page which INSERTS VALUES, then the code below works:
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize ,function(data){
alert("data");
});
}
So I thought to be able to submit the form and add a row into the database, if I do this code below then it should work but it doesn't. It submits the form but does not add a row in the database. How can this code be fixed so it submits the form and also add a row in DB? Below is the code
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize ,function(data){
alert("data");
});
var QandAO = document.getElementById("QandA");
QandAO.submit();
}
InsertQuestion.php looks like this below:
<?php
session_start();
$username="xxx";
$password="xxx";
$database="xxx";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$insertquestion = array();
$insertquestion[] = "' ". mysql_real_escape_string( $_POST['id'] ) . "'";
$questionsql = "INSERT INTO Question (SessionId)
VALUES (" . implode('), (', $insertquestion) . ")";
mysql_query($questionsql);
mysql_close();
?>
I think the problem is that the second part of your code (the form submit) cuts off the first part before it's complete. Give the AJAX call a chance to finish by putting the form submit inside the AJAX callback:
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize ,function(data){
alert("data");
var QandAO = document.getElementById("QandA");
QandAO.submit();
});
}

Categories