I got some problems with my code. I want to delete multiple data from MySQL database that populate from Select Option.
Example: I select data with id 5, 2, 4, then press the delete button, it only deletes the latest id which is 5.
Can I know what is the problem? Below is my code:
index.html
<?php
include("configPDO.php");
$smt = $conn->prepare("SELECT * FROM frame_list ORDER BY framework_name ASC");
$smt->execute();
$results = $smt->fetchAll();
?>
<form method="post" id="multiple_select_form">
<select name="framework[]" id="framework" class="form-control selectpicker" data-live-search="true" multiple>
<?php foreach ($results as $row2): ?>
<option value= <?php echo $row2["framework_id"]; ?>><?php echo $row2["framework_name"];?></option>
<?php endforeach ?>
</select>
<br><br>
<input type="hidden" name="framework_id" id="framework_id" />
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</form>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
$('#framework').change(function(){
$('#framework_id').val($('#framework').val());
});
$('#multiple_select_form').on('submit', function(event){
event.preventDefault();
if($('#framework').val() != '')
{
var form_data = $(this).serialize();
$.ajax({
url:"delete.php",
method:"POST",
data:form_data,
success:function(data)
{
//console.log(data);
$('#framework_id').val('');
$('.selectpicker').selectpicker('val', '');
alert(data);
}
})
}
else
{
alert("Please select framework");
return false;
}
});
});
</script>
delete.php
<?php
include("configPDO.php");
$smt = $conn->prepare("DELETE FROM frame_list WHERE framework_id = '".$_POST["framework_id"]."'");
$smt->execute();
if($smt){
echo "Data DELETED";
}else{
echo "Error";
}
?>
Appreciate it if anyone can solve my problem.
Thank you very much.
this is where framework id got overwritten:
$('#framework').change(function(){
$('#framework_id').val($('#framework').val());
});
delete.php will only run when your ajax request send(in this case, when you click submit button).
so maybe you'll want to pass several id at a single request if you want delete them at the same time. or you may want to delete them one by one by sending the ajax request each time you choose a id.
Related
I want to stop page refresh after the user submits the form. The problem is that it doesn't seem to work.
PHP:
<?php
function displayimage() {
$con = mysqli_connect("localhost", "root", "", "cookbook");
$result = mysqli_query($con, "SELECT * FROM product");
while ($row = mysqli_fetch_array($result)) {
echo "<img src='uploads/".$row['image']."' class='imageaaa'>";
}
mysqli_close($con);
}
function addrecipe() {
$con = mysqli_connect("localhost", "root", "", "cookbook");
if (isset($_POST["Add"])) {
if (!empty($_POST["Name"])
){
$name = $_POST["Name"];
$type = $_POST["Type"];
$image = $_FILES['Image']['name'];
$date = date("d.m.Y, G:i");
$sql = "
INSERT INTO
product(`name`, `type`, `image`, `date`)
VALUES('$name', '$type', '$image', '$date');
// More Insert Into queries
";
$target = "uploads/".basename($image);
if (move_uploaded_file($_FILES['Image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
} else {
$msg = "Failed to upload image";
}
$var = mysqli_multi_query($con,$sql);
if($var){
echo "good";
} else {
echo "bad";
}
} else {
echo "Fill in the form";
}
}
mysqli_close($con);
}
?>
HTML:
<?php
addrecipe();
displayimage();
?>
<form method="POST" id="form" enctype='multipart/form-data'>
Name:
<input type="text" name="Name" value="<?php echo isset($_POST['Name'])?htmlspecialchars($_POST['Name'], ENT_QUOTES):'';?>"><br>
Type:
<select name="Type" required>
<option value="dishes" disabled selected hidden required>Wybierz typ</option>
<option value="dishes">Dania</option>
<option value="desserts">Desery</option>
<option value="snacks">Przekąski</option>
</select><be>
Image (jpg, png):
<input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('upload_image').click();" />
<input type="file" style="display:none;" id="upload_image" name="Image">
<br><be>
<!-- More text inputs -->
<button name="Add" id="add">sdfsdfsd</button>
<script>
$("#add").submit(function(e) {
e.preventDefault();
});
</script>
</form>
I've tried a few things, but nothing seems to work. Everything works ok, data is sent to the database, but I can't get rid of this page reload. Did I do something wrong? If there is a better solution I'd love to know it. Also, I have this js code:
<script>
if (window.history.replaceState){
window.history.replaceState(null, null, window.location.href);
}
</script>
After my HTML tag, deleting it changes nothing. It disables the resubmit form pop-up before you refresh the page.
Is there any way I can disable page refresh after form submission?
The <script> tag should be outside of the <form> tag and should contain #form instead of #add
...
</form>
<script>
$("#form").submit(function(e) {
e.preventDefault();
});
</script>
The .submit() method is applied on the form element.
You can also achieve the same by simply returning false from the handler as mentioned in the spec.
...
</form>
<script>
$("#form").submit(() => false);
</script>
I have an problem, I have multiple button generate with while, with different names (button[$nostation]).
Now, I want to update MySQL database (table: smt, column: no) with the same id ($nostation).
How I can generate AJAX function for that?
This is my code:
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
echo "
<div class='col-xs-2-2'>
<form action='coba.php' method='post'>
<button name='button[$nostation]' value='2' style='background-color:#02780d; width:140px; height:75px; margin : 2px; border-radius:10%;'>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
";}?>
And this is my code for update database with PHP:
<?php
include 'connect.php';
$array=$_POST['button'];
foreach ($array as $nostation => $value) {
$updch=mysqli_query($connect,"UPDATE smt SET status='$value' WHERE no='$nostation'");
}?>
How I can update with AJAX without refreshing the page?
View Part :-
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
?>
<div class='col-xs-2-2'>
<form method='post'>
<input type="hidden" value="<?php echo $nostation;?>" id="name_<?=$nostation;?>" name="name">
<button type="submit" id="button_<?=$nostation;?>" data-id="<?=$nostation;?>">SAVE</button>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
<?php } ?>
jQuery / AJAX Part:-
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ //when DOM is Ready.
$("[id^=button_]").click(function () { //when Button is Clicked.
var id = $(this).data('id'); // Get the ID of the button that was clicked on.
var name = $("#name_"+id).val(); // value from `input` which is connected the clicked button.
// console.log(id+"---"+name);
$.ajax({ // AJAX request
url: 'update.php', // send request to server.
method: 'POST', // method is POST.
data: { //data which is sent to server.
id: id,name: name
},
success: function (data) { //success function called.
alert(data); // alert success data.
}
});
});
});
</script>
update.php:-
And in the php-side We catch it by:-
echo $id = $_POST['id'];
echo $name = $_POST['name'];
//use update query.
Note:- For more info regarding click()
https://api.jquery.com/click
Now I create a system that can delete multiple data using select option. But here I got some issues. When i only select one data, and press button delete, it will delete. But if I choose more than one data, for example, 3 data, it will only delete the latest id of the data. Below is my the image
And below is my code:
index.php
<form method="post" id="multiple_select_form">
<select name="framework" id="framework" class="form-control selectpicker" data-live-search="true" multiple>
<?php foreach ($results as $row2): ?>
<option value= <?php echo $row2["framework_id"]; ?>><?php echo $row2["framework_name"];?></option>
<?php endforeach ?>
</select>
<br /><br />
<input type="hidden" name="framework_id" id="framework_id" />
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</form>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
$('#framework').change(function(){
$('#framework_id').val($('#framework').val());
});
$('#multiple_select_form').on('submit', function(event){
event.preventDefault();
if($('#framework').val() != '')
{
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
//console.log(data);
$('#framework_id').val('');
$('.selectpicker').selectpicker('val', '');
alert(data);
}
})
}
else
{
alert("Please select framework");
return false;
}
});
});
</script>
insert.php
<?php
include("configPDO.php");
$smt = $conn->prepare("DELETE FROM frame_list WHERE framework_id = '".$_POST["framework_id"]."'");
$smt->execute();
if($smt){
echo "Data DELETED";
}else{
echo "Error";
}
?>
Can anyone knows how to solve this problem? Thanks
framework will hold one value every time.
Use input arrays -
Change name="framework" to name="framework[]".
and in query -
WHERE framework_id in ('". implode("','", $_POST["framework_id"]) ."')"
Try to use parameter binding for security.
I am confused as to why my select is not passing any post data to the results page. If I run var_dump($_POST); the select (#boxdest or #boxdest2) is not being displayed. Is there some special way to pass select to php results page. What I normally do is as an example: $var=$_POST['boxdest'];. Problem is the select is not being sent from original code. I have posted my code and would be grateful if someone could show me where I have gone wromg. Many thanks.
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("sample",$conn);
$result = mysql_query("SELECT * FROM boxes where department = '{$_GET['dept']}'");
?>
<select id="boxdest" name="boxdest[]"size="7">
<?php
$i=0;
while($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row["custref"];?>"><?php echo $row["custref"];?></option>
<?php
$i++;
}
?>
</select>
<input type="button" id="submit2" name="submit2" value=">" />
<input type="button" id="submit3" name="submit3" value="<" />
<select id="boxdest2" name="boxdest2[]" size="7"></select>
<script type="text/javascript">
$("#submit2").click( function()
{
//alert('button clicked');
$box1_value=$("#boxdest").val();
$box1_text=$("#boxdest option:selected").text();
$("#boxdest2").append('<option value="'+$box1_value+'">'+$box1_text+'</option>');
$("#boxdest option:selected").remove();
});
$("#submit3").click( function()
{
//alert('button3 clicked');
$box2_value=$("#boxdest2").val();
$box2_text=$("#boxdest2 option:selected").text();
$("#boxdest").append('<option value="'+$box2_value+'">'+$box2_text+'</option>');
$("#boxdest2 option:selected").remove();
}
);
</script>
So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique