How can I cancel delete action with confirm prompt window? - php

After I click "Cancel" in the alert window, the delete is still happening!
How can I solve this?
I am using MySQL database.
Working test ToDo list: http://qrmobile.net/todo/index.php
Delete code below, then index page code...
NEW CODE SNIPPET BELOW: Is ajax giving me the problem?
// Delete entry
$('a.deleteEntryAnchor').click(function() {
var thisparam = $(this);
thisparam.parent().parent().find('p').text('Please hold your onions.... ☺');
$.ajax({
type: "GET",
url: thisparam.attr('href'),
success: function() {
thisparam.parent().parent().fadeOut('fast');
}
});
return false;
});
require 'db.php';
$db = new Db();
$response = $db->delete_by_id($_GET['id']);
header("Location: index.php");
<div id="container">
<header><img src="/todo/images/heading-trans.gif"></header>
<ul id="tabs">
<li id="todo_tab" class="selected">
To-Do
</li>
</ul>
<div id="main">
<div id="todo">
<?php
require 'db.php';
$db = new Db();
$query = "SELECT * FROM todo ORDER BY id asc";
$results = $db->mysql->query($query);
if($results->num_rows) {
while($row = $results->fetch_object()) {
$title = $row->title;
$description = $row->description;
$id = $row->id;
echo '<div class="item">';
$data = <<<EOD
<h4>$title</h4>
<p>$description</p>
<input type="hidden" name="id" id="id" value="$id" />
<div class="options">
<a class="deleteEntryAnchor" href="delete.php?id=$id">Delete</a>
<a class="editEntry" href="#">Edit</a>
<a class="save-button" href="index.php">Save</a>
</div>
EOD;
echo $data;
echo '</div>';
} // end while
}
else {
echo "<p>There are zero items. Add one now! </p>";
}
?>
</div><!--end todo-->
<div id="addNewEntry">
<h2>Add New Entry</h2>
<form action="addItem.php" method="post">
<p><label for="title"> Title</label>
<input type="text" name="title" id="title" class="input" required/></p>
<p><label for="description"> Description</label>
<textarea name="description" id="description" required></textarea></p>
<p><input type="submit" name="addEntry" id="addEntry" value="Add New Entry" /></p>
</form>
</div><!--end addNewEntry-->
</div><!--end main-->
</div><!--end container-->
<script>
//Do all this when the DOM is loaded
$(function() {
//get all delete links (Note the class I gave them in the HTML)
$("a.deleteEntryAnchor").click(function() {
//Basically, if confirm is true (OK button is pressed), then
//the click event is permitted to continue, and the link will
//be followed - however, if the cancel is pressed, the click event will be stopped here.
return confirm("Are you sure you want to delete this?");
});
});
</script>

Its basically your js is where the issue lies and needs a preventDefault, I assume, and its not really returning anything to any function that stops the form post.
$("a.deleteEntryAnchor").click(function(e){
if(!confirm("Are you sure you want to delete this?")){
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class='deleteEntryAnchor' href='www.stackoverflow.com'>delete</a>

$(function() {} only guards against the situation where your javascripts try to do things before the DOM has finished loading.
On big pages, it's entirely possible that your user clicks that link so fast that no javascripts have been loaded. So the browser is half way loading the page, the user issued a command to go to a different link, so it does the right thing by redirecting the user, instead of finish loading the current page.
You will want to have either have a return false on the onclick attribute of the anchor (safest) or e.preventDefault() in the jQuery click function.

Related

Can only delete first row with Ajax

I have a page that prints out rows from a mysql table. I'm trying to create an ajax form that allows users to delete rows but for some reason I can only seem to get it to delete the very top row that is printed out.
I've only included the script that might be needed here and left out the database query(which works fine).Firebug only shows my form being posted when I click the top row of results, any other rows it does nothing. Can anyone tell me what's wrong? Thanks
My_reviews.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
//Delete Review
$(document).ready(function(){
$("#deleteReview").click(function (e) {
e.preventDefault();
var username=$("#username").val();
var film_id=$("#film_id").val();
var id=$("#id").val();
$.post('ajax_deleteReview.php', {username: username, film_id: film_id, id: id},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
return false;
});
});
</script>
</head>
<div class="container">
<div id="message"></div>
<?php
$sql = "SELECT * FROM user_reviews WHERE username='$username' ORDER BY DATE desc";
$result = $db_conx->query($sql);
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$film_id = $row['film_id'];
$review = $row['review'];
$movie = $tmdb->getMovie ($film_id);
echo '
<div class="row">
<div class="col-md-1">
<img id="image1" src="'. $tmdb->getImageURL('w150') . $movie->getPoster() .'" width="80" />
<p>
</p>
</div>
<div class="col-md-4">
<h3>
' . $movie->getTitle() .'
</h3>';
echo'
<p>
'.$review. '
</p>
<form>
<input type="hidden" id="username" name="username" value="'. $username.'">
<input type="hidden" id="film_id" name="film_id" value="'.$film_id .'">
<input type="hidden" id="id" name="id" value="'.$id .'">
<button type="submit" id="deleteReview" class="btn btn-danger btn-xs pull-right">delete</button>
</form>
</div>
<div class="col-md-7">
</div>
</div>';
}
?>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js">
</script>
</div>
</body>
</html>
ajax_deleteReview.php
<?php
//include db configuration file
include_once("ajax_review/config.php");
//Configure and Connect to the Databse
$username=$_POST['username'];
$film_id=$_POST['film_id'];
$id=$_POST['id'];
//Delete Data from Database
$delete_row = $mysqli->query("DELETE * FROM `user_reviews` WHERE id='$id' AND username='$username' AND film_id='$film_id' LIMIT 1");
if($delete_row){
echo '<img src="images/tick_large.png"/>';
}
else{ echo "An error occurred!"; }
?>
You have duplicated IDs in inputs, so jQuery returns the 1st occurrence of input.
You can add film_id, id and film_name to the <a> link with a data attribute, then read with jquery.
JavaScript function for ajax request need to be assigned to the class:
$(".deleteReview").click(function (e) {...
and
<a class="deleteReview"....
so with this you eliminate duplicate IDs in HTML code.

php var to jquery failing to update after page reload

Know a lot about php but novice at jquery or javascript and I'm trying to update a variable after a form submit.
I have a form that submits to a php page.
<form name="FindUser" id="userform" class="invoform" method="post" action="" />
<div id ="userdiv">
<p>Name (Lastname, firstname):</p>
<input type="text" name="username" id="username" class="inputfield" />
<input type="submit" name="find" id="find" class="find" value="Find" />
</div>
</form>
Which is echoed back via the below method:
<div id="infowrapper">
<div id="usernameinfo" class="info">
<?php
if(isset($_POST['find'])){
include('includes/find.php');
}
?>
</div>
</div>
One of the vars that comes back from the php page is
$hidefields="1"
The problem is although I can see php update the var correctly, jquery does not update with this new value. I've tested with an alert box which still displays the var as 0 while php is echoing it as a 1. I can only assume it's cached or something.
<script>
$(document).ready(function(){
$("#userform").hide();
});
$(document).ready(function(){
var hide = <?php echo $hidefields; ?>;
if(hide == 1){
$("#userform").hide();
$("#infowrapper").show();
$("#passwordreset").show();
$("#enabledisable").show();
}
else {
$("#userform").show();
$("#infowrapper").hide();
$("#passwordreset").hide();
$("#enabledisable").hide();
}
alert(hide);
});
</script>
Is there some simple line I can add to get jq to update with this new var? I'm so close to getting this finished and it's the last obstacle in a steep learning curve. Then I can do some sweet powershell integration ^^.
Thanks.
You can reduce this a bit :
$(document).ready(function(){
$("#userform").hide();
});
$(document).ready(function(){
var hide = <?php echo $hidefields; ?>;
function firstAction(){
$("#userform").hide();
$("#infowrapper,#passwordreset,#enabledisable").show();
}
function secondAction(){
$("#userform").show();
$("#infowrapper,#passwordreset,#enabledisable").hide();
}
hide == 1 ? firstAction() : secondAction();
alert(hide);
});

Ajax Load - Form Submission

I have a website I'm building and it is set up so that when a link is pressed on the left, the page content is loaded in a div on the right.
<div id="right-column">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
var dataReturn='';
function makeRequest(url){
$('#preloader').show();
$.get(url, function(data) {
$('#resultDiv').html(data);
$('#preloader').hide();
});
}
function makePostRequest(url, params){
$('#preloader').show();
$.post(url,params, function(data){
$('#resultDiv').html(data);
$('#preloader').hide();
});
}
</script>
</head>
<body>
<div id="preloader"></div>
<div id="resultDiv">
<h3>Welcome <?php echo $user_identity;?></h3>
<h5>Message: <?php echo $wpdb->get_var("SELECT message FROM staff_misc");?></h5>
</div>
</div>
Now this works fine for the links loading the content they're supposed to... now my question is. One of the pages has a form with the following code:
<h3>Admin Message</h3>
<form id="message" method="post" action="Admin/message.php">
<input type="text" style="width:700px;" value="Set A New Message" name="admin-message"/>
<input class="submit" type="submit" name="submit" value="Submit">
</form>
<?php
if ( isset ( $_POST['submit'] ) ) //If submit is hit
{
$message = $_POST["admin-message"];
$wpdb->query("UPDATE staff_misc set Message = '$message' where id = '1'");
?><b>New Message Set:</b> <?php echo $wpdb->get_var("SELECT message FROM staff_misc");?><?php
}
If that form is submitted, it refreshes the whole page rather than reloading the content back in to the AJAX div. How do I go about making it so that page loads back in to the AJAX div rather than refreshing the entire page and losing the left column with the links.
You can either capture the submit event on the form, cancel the default action, and redirect it to your own form handler, then submit via AJAX.....or you can change the submit button to a regular button that calls your form handler, then submit via AJAX.
I think it would be something like this:
<script>
$("#message").submit(function() {
// do something...
// this will prevent the event from bubbling and keep the page from refreshing
return false;
});
</script>
You should have a submit handler for that form, and make sure to return false at the end of your function, to stop the default action for the form.
$('#message').on('submit', function() {
$.post('Admin/message.php', $('#message').serialize(), function( html ){
// do something with return message
});
return false;
});
First Page:
<h3>Admin Message</h3>
<form id="message" method="post" action="Admin/message.php">
<input type="text" style="width:700px;" value="Set A New Message" name="admin-message" id="admin-message" />
<input class="submit" type="submit" name="submit" value="Submit">
</form>
<div id="result"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(".submit").click(function(e){
//Prevent the entire page from refreshig
e.preventDefault();
$.get("ajax.php?admin-message=" + $("#admin-message").val(), function(result){
$("#result").html(result);
});
});
</script>
ajax.php
<?php
if ( isset ( $_POST['submit'] ) ) //If submit is hit
{
$message = $_POST["admin-message"];
$wpdb->query("UPDATE staff_misc set Message = '$message' where id = '1'");
?><b>New Message Set:</b> <?php echo $wpdb->get_var("SELECT message FROM staff_misc");?><?php
}
?>

Jquery dialog box error

I am using a dialog box to display and submit a enquiry form on my page.I am having problem when I try to call it again and again.The first time everything works fine and the form s submitted successfully.But if I click the GO button(added html below).I get an error for this line document.
EDITED:
<div class="hidden" id="dialog">
<form action="index.php" class="testForm" id="testForm">
<div class="name" id="name">
<div class="displayName" id="dispName">Name</div>
<div class="textName" id="viewName"><input type="text" class="fname" id="fullName" /></div>
<div class="hide" id="nameErr"></div>
</div>
<div class="address" id="addressDetails">
<div class="displayAddress" id="dispAddress">Address</div>
<div class="textAddress" id=""><input type="text" class="taddress" id="fullAddress" /></div>
<div class="hide" id="addressErr"></div>
</div>
<div class="submitForm" ><input type="button" class="submitDetails" id="submitInfo" name="Submit" value="Submit" onClick="validateAndSubmitForm()"/>
<a name="Close" onclick="$('#dialog').dialog('close');">Close</a>
</div>
</form>
</div>
Javascript\jquery
function submitEnquiryForProperty()
{
document.forms.testForm.reset();
$("#dialog").dialog({
modal:true,
resizable:false,
autoOpen:false,
width:260,
});
openDialog();
}
function openDialog(){
$("#dialog").dialog("open");
}
function closeDialog(){
$("#dialog").dialog("close");
}
Callback function on form submit
$.ajax({
type:'POST',
url:"processForm.php",
data:"name="+name+"&address="+address,
dataType:"html",
success:function(msg){
if(msg=="success"){
$("#dialog", window.parent.document).html("<div class='pad5'><div class='flt' style='padding-left:3px; width:235px;'><div class='thanx_msg'>Thank you for submitting the details. <br /><div class='spacer5'> </div><span class='gre'>Our Sales team shall revert to your query soon.</span></div></div><div class='spacer5'> </div><div style='padding-left:3px;' class='text'><strong>You can also:</strong></div><div style='margin-left:20px; line-height:20px;'>• Apply for a <a href='homeloan.php'>Home Loan</a><br />• Visit <a href='http://www.proptiger.com'>proptiger.com</a> for more properties<br />• See our <a href='http://www.proptiger.com/blog'>Blog</a> for latest updates</div></div><br/><div class='msg' style='color:red;'>Click to close the box</div>");
$(function(){
$('#dialog').click(function() {
closeDialog();
});
});
}
else
{
alert("Operation cannot be completed,please try again");
}
}
But I am facing the same problem.Error at the .reset() line.
Thanks for your time.
Updated answer
If you want to have a reusable dialog, do it like this:
Include the dialog element (almost assuredly a <div>) in your initial HTML. Use a CSS class so that it will not be immediately visible, for example:
HTML:
<div id="dialog" class="hidden">...</div>
CSS:
.hidden { display: none }
Unconditionally call $("#dialog").dialog(options) from Javascript immediately after the page loads. Be sure to set autoOpen: false in the options.
Whenever you want to display the dialog, use $("#dialog").dialog("open").
Whenever you want to hide the dialog, use $("#dialog").dialog("close").
Repeat steps 3 and 4 as much as you like.
.dialog( "destroy" )
Remove the dialog functionality completely. This will return the element back to its pre-init state.
.dialog( "close" )
Close the dialog.

Update div on AJAX submit jQuery is updating all divs

I'm trying to update a div with an ajax post. Problem is...it's updating every div.
Here's the json.php:
//json.php
$data['months'] = $db->escape_value($_POST['check']);
$data['id'] = $db->escape_value($_POST['hidden']);
$query = "UPDATE month SET months = '{$data['months']}' WHERE monthID = '{$data['id']}'";
$result = $db->query($query);
if($result) {
$data['success'] = true;
$data['message'] = "Update Successful!";
$data['text'] = $_POST['check'];
echo json_encode($data);
} else {
$data['message'] = "Update could not be completed.";
}
And the html:
<?php
$query = $db->query('SELECT * FROM month');
?>
<html>
<head>
<title>jQuery/Ajax - Update is updating all divs</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input.check, button.save, input.cancel, div.message").hide();
$(".edit").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").hide();
$(this).parent().siblings("li.liThree").children("button.save").show();
$(this).parent().siblings("li.liFour").children("input.cancel").show();
$(this).parents("ul").siblings("div.showText").hide();
$(this).parents("ul").siblings("input.check").show();
$(this).hide();
return false;
});
$(".cancel").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").show();
$(this).parent().siblings("li.liThree").children("button.save").hide();
$(this).parent().siblings("li.liOne").children("input.edit").show();
$(this).parents("ul").siblings("div.showText").show();
$(this).parents("ul").siblings("input.check").hide();
$(this).hide();
return false;
});
$("form[name=form1]").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText").html(data.text);
$(".message").html(data.message).slideDown("fast");
$(".check").hide();
$("button.save").hide();
$(".cancel").hide();
$(".edit").show();
$(".delete").show();
$(".showText").show();
return false;
}
}, "json");
return false;
});
});
</script>
</head>
<body>
<div class="message">message</div>
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
<div class="container">
<div class="showText"><?php echo $row['months']; ?></div>
<input name="check" type="text" class="check" value="<?php echo $row['months']; ?>" />
<input name="hidden" type="hidden" class="hidden" value="<?php echo $row['monthID']; ?>" />
<ul class="list">
<li class="liOne">
<input name="edit" type="button" class="edit" value="edit" />
</li>
<li class="liTwo">
<input name="delete" type="submit" class="delete" value="delete" />
</li>
<li class="liThree">
<button name="save" type="submit" class="save" value="<?php echo $row['monthID']; ?>">save</button>
</li>
<li class="liFour">
<input name="cancel" type="button" class="cancel" value="cancel" />
</li>
</ul>
</div>
</form>
<?php } ?>
<!--<a id="reset" href="test3.php">reset</a>-->
</body>
</html>
You need to specify a context (the form) for the elements you're changing:
$("form[name=form1]").submit(function(){
var form = this;
var params = $(this);
$.post(form.action, { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText", form).html(data.text);
$(".message", form).html(data.message).slideDown("fast");
$(".check", form).hide();
$("button.save", form).hide();
$(".cancel", form).hide();
$(".edit", form).show();
$(".delete", form).show();
$(".showText", form).show();
return false;
}
}, "json");
return false;
});
Also, if you hide a parent element, the children are hidden, too, so you probably want to do that...
Every div has the same class: showText. They need unique IDs instead, like Div1, Div2. Then update them by their ID: $("#Div1")
Hint, instead of answer:
How many elements does $(".showText") return?
2nd Hint: It's more than one!
===
Edit for more clarity:
The first issue is that you're selecting by classes like .showText. But you're creating multiple forms, each of which has an element that matches .showText. You need some way to point at the right element in each form. One way to solve this is to add an ID on each FORM tag, so you can then select things like $('#form-number-$N .showtext) -- which selects any elements with class="showtext" inside the element with id "#form-number-$N"
You're looping over rows in your database and writing the forms. So you need some variable data to identify each individual form.
You've got a while loop that populates $row:
<?php while($row = $db->fetch_assoc($query)) { ?>
But currently, every form you create has a name attribute of "form1".
So what if, instead of:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
You did something like:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form<?PHP echo $row['id']; ?>" id="<?PHP echo $row['id']; ?> class="myFormClass" method="post">
Then you could use a handler that looks something like:
$("form.myFormClass").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(this.id + " .showText").html(data.text);
...
return false;
}
}, "json");
return false;
});
Do you see what's happening there?

Categories