Form not submitting after bootstrap confirmation - php

Firstly I will apologise my knowledge of jquery/javascript is not very good so my mistake maybe very obvious to some but I am still learning so be gentle!
I have a form which allows the members to delete posts they have made from the database. The form works fine and using php deletes the data from the database as I want. I wanted to create a popup that gets the user to confirm thats what they would like to do. I don't want to use the bog standard browser specific onclick method I wanted something a bit more customisable. So I am trying to use bootbox, I currently have the confirmation box popping up onclick but when you select yes, nothing else happens. I suspect the result from the jquery is not firing the form but from what I have read my code for that part is good?
I have pasted below my php, jquery and html
PHP:
<?php
$deletepost = 'none';
$deleteposterror = 'none';
if(isset($_POST['delete'])) {
$del_topic_id = $_POST['topic_id_value'];
// sql to delete a record
$pass_fail = "DELETE FROM topics WHERE topic_id ='$del_topic_id';";
$pass_fail .= "DELETE FROM posts WHERE topic_id_post ='$del_topic_id'";
if (mysqli_multi_query($conn, $pass_fail)) {
$deletepost = 'show';
}else{
$deleteposterror = 'show';
echo "ERROR: Could not able to execute $pass_fail. " . mysqli_error($conn);
}
}
?>
HTML & PHP in while loop:
<?php
$sql1 = "SELECT * FROM topics WHERE topic_by = '".$id."' ORDER BY topic_date DESC ";
$result1 = mysqli_query($conn, $sql1);
while($row = $result1->fetch_assoc()) {
$topic_id = $row ['topic_id'];
$topic_subject = $row ['topic_subject'];
?>
<div class='chat_post_titles' >
<div class='row'>
<div class='col-md-7 chat_post_text_align_left'>
<?php echo $topic_subject?>.
</div>
<div class='col-md-2 chat_post_text_align_right'>
<?php
$my_date = $row['topic_date'];
$date = DATE("G:i:s d/m/Y",strtotime($my_date));
?>
<div class='hide_text'>Post Date: </div>
<?php echo $date?>
</div>
<div class='col-md-2 chat_post_text_align_centre'>
<div class='hide_text'>Delete Post: </div>
<form method="post" class="delete_post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="hidden" name="topic_id_value" id="topic_id_value" value="<?php echo $topic_id?>">
<button type="submit" name="delete" id="delete" class="btn btn-danger buttonElement">Delete</button>
</form>
</div>
</div>
</div>
<?php
}
?>
JQUERY at bottom of page:
</body>
<?php include("../PHP/js.php"); ?>
<script type="text/javascript" src="../Members/updatedetails.js"></script>
<script type="text/javascript" src="../Members/bootbox.min.js"></script>
<script>
$('form').on('click','button.buttonElement',function (e) {
var form = $(this).closest('form'); // <-- add this
e.preventDefault();
bootbox.confirm({
message: "Are you sure you want to delete your post?",
title: "Delete Post",
buttons: {
cancel: {
label: "No",
className: "btn btn-default"
},
confirm: {
label: "Yes",
className: "btn btn-default"
}
},
callback: function(result) {
if(result == true) {
form.submit();
}
}
});
});
</script>
</html>

Finally worked out why my code wasn't working in my php I was using
if(isset($_POST['delete']))
but when using javascript submit() function this name attr is removed. So I used the name of the hidden input like so if(isset($_POST['topic_id_value'])) and it worked as normal.
Still thanks to the guys that gave me advice

Related

Ajax code not working even if it is (i think) correct

The function that this do is when the user clicked the button, it will execute the Ajax codes and then get the value of the input and send it to the PHP file and then send it back to the Ajax code to display the message from the MySQL table.
I tried changing my codes, changing div ids, changing syntax, clearing block of codes but none seems to work.
AJAX
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('input[name=message]').val();
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
HTML UPDATED
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<form method="POST">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</form>
</div>
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
PHP UPDATED
<?php
include 'database/connect.php';
session_start();
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$_POST[message]%' OR '$_POST[message]%_' OR '$_POST[message]_'";
$result = $conn->query($sql);
if ($row = $result->fetch_assoc()) {
echo "Hi ". $_SESSION['name'] .".<br> " . $row['message'];
}
?>
Changes with suggestion(in comment):-
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</div><!-- form not requird -->
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
<!-- Add jquery library so that jquery code wiil work -->
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('#msg').val(); // id is given so use that, its more easy
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
automatedchat_func.php(must be in the same working directory where your above html file exist)
<?php
error_reporting(E_ALL);// check all type of error
ini_set('display_errors',1);// display all errors
include 'database/connect.php';
session_start();
$final_result='';//a variable
if(isset($_POST['newmsg']) && !empty($_POST['newmsg'])){// its newmsg not message
$message = $_POST['newmsg'];
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$message%' OR '$message%' OR '$message'"; // check the change ere
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) { // while needed
$final_result .="Hi ". $_SESSION['name'] .".<br> " . $row['message']."<br>";
}
}else{
$final_result .="Hi please fill the input box first";
}
echo $final_result; // send final result as response to ajax
?>
Note:- your query is still vulnerable to SQL Injection. So read for prepared statements and use them

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.

How can I cancel delete action with confirm prompt window?

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.

Display records on load page using jquery ajax in php

I want to load data when page is loaded but if i try doing that then delete function doesn't work and whenever I insert the effect should be seen in table without refreshing page Please check my code what changes to be done in this
index.php
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#Submit").click(function(e) {
var name = $('#name').val();
var message=$('#message').val();
if($(":text").val().length==0)
{
$(":text").after('<span class="error">Field cannot be empty</span>');
$('#name').addClass('error');
$('#message').addClass('error');
return;
}
else{
$('#name').removeClass('error');
$('#message').removeClass('error');
//$('#propspectDiv').removeClass('error');
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');
$.ajax({
url : 'data.php',
data:{
"name" : name,
"message" : message
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
},
complete:function(){
$('#myform').each(function(){
this.reset();
});
}
});
}
});
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
});
</script>
</head>
<body>
<form id="myform">
<div id="wrapper">
Name : <input type="text" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Submit" id="Submit" />
<div id="propspectDiv"></div>
<table id="data" border="1" style="display:none;"></table>
</div>
</form>
</body>
data.php
<?php
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
include('connection.php');
$sql = "INSERT INTO login (username,message) VALUES ('$name','$message')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td id=td1>
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
echo '</tr>';
$i++;
}
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: index.php");
}
?>
Looks like your grabbing the ID attribute of the link, but not setting it...
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
There is no ID attribute on your existing delete link:
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
Also - you probably don't need to have the link href pointing to delete.php as its irrelevant when the jquery click event does all the work.
Also, because you are inserting the html (including the delete method) via jquery you may need to use the "on" event
I'm doing this off the cuff so the code may have some minor bugs but I believe this is the path you want to take...
Revised it might look like this:
JQUERY
$("a").on("click", function(e) {
e.preventDefault();
$.post('delete.php',{ id: $(this).attr("id")});
return false;
});
LINK
echo"<td id=td1>
<a id='".$row['id']."' href='#'>Delete</a>";
echo '</tr>';
couple things to note...
1 - above i'm not actually VERIFYING the record was deleted before I remove the appropriate table row - you may want to implement something to check this
2 - an alternative to removing the table row would be to just update the table in general by repulling the data and outputting it - if you know what i mean

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