I have this code which delete from database rows.But it removes one by one when pressing delete, checkbox not working.I want to multiple delete by checking checkbox.
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
function check() {
document.getElementById("myCheck").checked = true;
}
function uncheck() {
document.getElementById("myCheck").checked = false;
}
HTML
<a href="javascript:confirmDelete('?action=deleteurl&id=<?php echo $row[0]; ?>')">
<input type="checkbox" id="myCheck[]">delete</td>
PHP
<?php
if($_GET['action'] == "deletelink" && !empty($_GET['id']) && is_numeric($_GET['id'])) {
$result = mysql_query("SELECT * FROM books WHERE id='".intval($_GET['id']);
while ($row = mysql_fetch_array ($result) )
unlink("/home/me/public_html/upload/image/{$row['image']}");
}
Your logic is not for multiple delete
this should be html
<input type="checkbox" id="myCheck[]" class="multicheck" name="<?php echo $row[0]; ?>" value="<?php echo $row[0]; ?>">delete</td>
Multiple Delete</td>
and this should be javascript
function confirmMultiDelete() {
if (confirm("Are you sure you want to delete")) {
var str = [];
$.each(".multicheck:checked",function(){
str.push($(this).val());
});
ids = str.join(",");
document.location = '?action=deleteurl&id='+ids;
}
}
here is my approach.
You need some modification to do multiple delete as my approach.
First you have to put value in checkbox so you can get its value to
delete.
Second you have to add another button or action to delete multiple
record.
Your Code ( with Modification ):
HTML + PHP CODE
<a href="javascript:confirmDelete('?action=deleteurl&id=value="<?php echo $row[0]; ?>"')">delete
</a>
<input type="checkbox" class="delCheck" id="myCheck[]" value="<?php echo $row[0]; ?>">
</td>
<!-- This will generate html code like below -->
<!--
<td>
delete
<input type="checkbox" class="delCheck" value="1" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="2" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="3" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="4" id="myCheck[]" class="delCheck">
</td>
<td>
<input type="button" value="Delete" name="delete_value" id="delete_value" class="delCheck">
</td>
-->
<!-- Multiple Delete Button -->
<input type="button" id="delete_value" name="delete_value" value="Delete" />
Javascript + Jquery
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
$( document ).ready(function() {
$("#delete_value").on("click", function (e){
var ids = '';
$('.delCheck:checked').each(function(i){
ids += $(this).val() + ',';
});
// go to delete url with action delete_all_ur
confirmDelete('?action=delete_all_url&id='+ids)
});
});
PHP Delete Code:
if( #$_GET['action'] == "delete_all_url" )
{
$all_ids = $_GET['id'];
// Remove trailing ',' from IDs
$all_ids = trim($all_ids, ",");
// Temporary variable to check only integer value passes
$tempId = str_replace(",", "", $all_ids);
// Check id numeric or not
if ( is_numeric($tempId) ) {
$sql_query = "SELECT * FROM books WHERE id in (".intval($_GET['id'].")";
$result = mysql_query($sql_query);
while ($row = mysql_fetch_array ($result) )
unlink("/home/me/public_html/upload/image/{$row['image']}");
} else {
//echo 'errors';
}
}
Related
I'm not a dev, I never do it but for a specific thing I've made a web page where people can insert data into a sql database.
My code is working but I guess I can optimize it because I've made it from things I've found over the Internet and I would like to turn radio buttons into check boxes because it is a lot of buttons at the end when there are many lines.
Maybe there are things wrong because I have change names so there are no ref to my company.
<!DOCTYPE html>
<?php
include('Connexion_DB.php');
/* Queries */
if (isset($_POST['Btn_Mode1'])){
$req1 = "UPDATE DATABASENAME SET Mode1 = '".$_POST['Mode1']."' WHERE ID = '".$_POST['ID']."'";
$result1 = sqlsrv_query($con,$req1);
}
if (isset($_POST['Btn_Mode2'])){
$req2 = "UPDATE DATABASENAME SET Mode2 = '".$_POST['Mode2']."' WHERE ID = '".$_POST['ID']."'";
$result2 = sqlsrv_query($con,$req2);
}
if (isset($_POST['form1']))
{
$Status = 'Y';
$array = explode(PHP_EOL, $_POST['textareaname']);
foreach($array as $index=>$value) {
if($value === '') unset($array[$index]);
}
foreach ($array as $key => $value) {
$req = "INSERT INTO DATABASENAME (DATA, Active, Mode1, Mode2) VALUES ('".$value."','".$Status."', 'false','false');";
$result = sqlsrv_query($con,$req);
}
echo "<pre>";
echo print_r($array);
echo "</pre>";
}
if (isset($_POST['form2'])) {
foreach ($_POST['ID'] as $id) {
$req3 = "DELETE FROM DATABASENAME WHERE ID = '".$id."'";
$result3 = sqlsrv_query($con,$req3);
}
}
include('menu.php');
?>
<html>
<head>
<title>TITLE</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
</head>
<script>
$(function() {
$('.RadioBtn_Mode1').change(function() {
Mode1 = $(this).val();
ID = $(this).attr('id');
$.post( "Test_Page.php", {
Btn_Mode1: true,
ID: $(this).attr('id'),
Mode1: $(this).val()
} ).done(function( ) {
toastr.success(ID +' est a ' +Mode1);
});
});
});
$(function() {
$('.RadioBtn_Mode2').change(function() {
Mode2 = $(this).val();
ID = $(this).attr('id');
$.post( "Test_Page.php", {
Btn_Mode2: true,
ID: $(this).attr('id'),
Mode2: $(this).val()
} ).done(function( ) {
toastr.success(ID + ' est a ' +Mode2);
});
});
});
</script>
<body>
<div class="container body-container">
<div id='titre'class='titre'><h1>Insert Data</h1></div>
<form method='post' >
<input type="hidden" name="form1" />
<br />
<p>Data :</p>
<textarea name="textareaname" cols="60" rows="5"></textarea>
<br />
<br />
<input type="submit" value="Submit"/>
</form>
<form method="post" action="Test_Page.php">
<input type="hidden" name="form2">
<input type="submit" id="deleteBtn" value="Delete"/>
<div class="nav" id="inst1">
<table class="one">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Active</th>
<th scope="col">Data</th>
<th colspan="2">Mode1</th>
<th colspan="2">Mode2</th>
</tr>
</thead>
<tbody>
<?php
$req1 = "SELECT ID, Active, Data, Mode1, Mode2 FROM DATABASENAME" ;
$result1 = sqlsrv_query($con,$req1);
while($row1 = sqlsrv_fetch_array($result1))
{
echo "<tr>";
echo "<td><input type='checkbox' name = 'ID[]' value='" . $row1['ID'] . "'/></td>";
echo '<td>'.$row1['Active'].' </td>
<td>'.$row1['Data'].' </td>';
if ($row1['Mode1']=='False'){
echo '<td>False : <input class="RadioBtn_Mode1" id="'.$row1['ID'].'" name="RadioBtn_Mode1'.$row1['ID'].'" type="radio" value="False" checked/></td>';
echo '<td>True : <input class="RadioBtn_Mode1" id="'.$row1['ID'].'" name="RadioBtn_Mode1'.$row1['ID'].'" type="radio" value="True"/></td>';
} else {
echo '<td>False : <input class="RadioBtn_Mode1" id="'.$row1['ID'].'" name="RadioBtn_Mode1'.$row1['ID'].'" type="radio" value="False"/></td>';
echo '<td>True : <input class="RadioBtn_Mode1" id="'.$row1['ID'].'" name="RadioBtn_Mode1'.$row1['ID'].'" type="radio" value="True" checked/></td>';
}
if ($row1['Mode2']=='False'){
echo '<td>False : <input class="RadioBtn_Mode2" id="'.$row1['ID'].'" name="RadioBtn_Mode2'.$row1['ID'].'" type="radio" value="False" checked/></td>';
echo '<td>True : <input class="RadioBtn_Mode2" id="'.$row1['ID'].'" name="RadioBtn_Mode2'.$row1['ID'].'" type="radio" value="True"/></td>';
} else {
echo '<td>False : <input class="RadioBtn_Mode2" id="'.$row1['ID'].'" name="RadioBtn_Mode2'.$row1['ID'].'" type="radio" value="False" /></td>';
echo '<td>True : <input class="RadioBtn_Mode2" id="'.$row1['ID'].'" name="RadioBtn_Mode2'.$row1['ID'].'" type="radio" value="True" checked /></td>';
}
echo
'</td>
</tr>';
}
?>
</tbody>
</table>
</div>
</form>
</body>
</html>
<?php
sqlsrv_close($con);
?>
I would like a master to tell me what I can do better and help me to turn radio buttons into check boxes for the data insert.
SQL format table is BIT, so I want to insert true / false when I check/uncheck like I do with buttons.
Thanks !
Without rewriting all of the code in the answer
The idea of a checkbox, is marked or not. The input passed to the server by the browser, passes only if the checkbox is marked
So the the checkbox PHP code should check whether isset($_POST['RadioBtn_Mode2'] . $row1['ID']);
A simple reference here
Which is pretty much what you do already
All that's left is changing the echoing of the html, basically dropping one tag per
radio button, and changing the type to checkbox
For example, from this:
echo '<td>False : <input class="RadioBtn_Mode2" id="'.$row1['ID'].'" name="RadioBtn_Mode2'.$row1['ID'].'" type="radio" value="False" /></td>';
echo '<td>True : <input class="RadioBtn_Mode2" id="'.$row1['ID'].'" name="RadioBtn_Mode2'.$row1['ID'].'" type="radio" value="True" checked /></td>';
To This:
echo '<td>Check: <input class="RadioBtn_Mode2" id="'.$row1['ID'].'" name="RadioBtn_Mode2'.$row1['ID'].'" type="checkbox" value="False" /></td>';
Once that works, changing the universal name RadioBtn to CheckBx (or to anything else) is esthetics, of course
I have a table named description:
CREATE TABLE description(
word_id int(11),
word varchar (50),
PRIMARY KEY (word_id)
);
and I try to get all word in this table and for every word I create a checkbox with value and id equal at a value of the word that I get from table description,
if the checkbox is checked, I save his value in var abcd.
<?php
///connection
$get_word = $bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<br>
<script>
$('#<?php $donnees["word"] ?>').on('change', function() {
var abcd= this.checked ? this.value : '';
});
</script>
<?php
}
?>
Now, I want to create a button out of boocle while , if this button is clicked,it must give me the value of checkbox checked.
Here's how you could do it using jQuery. As you already have the PHP logic, my example demonstrates the jQuery code only:
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
console.log($(el).val())
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="Item 1">Item 1
<input type="checkbox" value="Item 2">Item 2
<input type="checkbox" value="Item 3">Item 3
<button id="getCheckedBoxes">Get checked boxes</button>
hope this will solve your problem
PHP code
<?php
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
JS CODE
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
var check_val = document.getElementById('myid_'+word).value;
alert(check_val);
}
}
</script>
or you can do this
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
alert(word);
}
}
</script>
add class name such as clickable to your input tag.
after all rendering in php add script that runs when any input with clickable class changed and you can get that tag!
<?php
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) { ?>
<input class="clickable" type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<?php } ?>
<script>
$('.clickable').on('change', function(item) {
console.log(item)
});
</script>
I try this
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<label><?php echo $donnees["word"] ?></label>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
<button id="getCheckedBoxes">Get checked boxes</button>
<script type="text/javascript">
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
alert($(el).val()) ;
})
})
})
</script>
And the alert message is empty,it don't show the value of checkbox chekced
I have these pages:
secondpage.php
<center>
Go back
<form action="fourthpage.php" method="POST">
<select name="what" class="what" required oninvalid="this.setCustomValidity('Please enter what are you paying for ')" oninput="setCustomValidity('')" />
<option value="" disabled selected>Choose what you are paying for</option>
<option>Something</option>
<option>Something</option>
<option>Something</option>
<option>Something</option>
</select>
<br>
<button>other...</button>
<br><br>
<label for="price">Type the price</label>
<br>
<input id="amount" name="price" placeholder="€" required oninvalid="this.setCustomValidity('Please enter the price ')" oninput="setCustomValidity('')" / type="number">
<br><br>
<label for="payment">Who has to pay for it:</label>
<br>
<label for="everybody">Everybody</label>
<input name="check_list[]" class="everybody" type="checkbox" value="everybody" onclick="ckChange(this)" required>
  
<label for="John">John</label>
<input name="check_list[]" class="John" type="checkbox" value="John" required>
  
<label for="Peter">Peter</label>
<input name="check_list[]" class="denis" type="checkbox" value="Peter" required>
  
<label for="Ferrari">Ferrari</label>
<input name="check_list[]" class="Ferrari" type="checkbox" value="Ferrari" required>
<br>
<input type="submit" name="submit" value="SEND">
</form>
</center>
fourthpage.php
<table>
<center><h1>John</h1></center>
<tr><td>WHO </td><td>WHAT </td><td>HOW MUCH</td><td>MY DEBT</td><td>TOTAL DEBT</td></tr>
<tr><td class="d"><?php if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected){
echo $selected."</br>";
}}} ?></td>
<td class="r"><?php if (isset($_POST['submit'])) { echo $_POST["what"];} ; ?></td>
<td class="a"><?php if (isset($_POST['submit'])) { echo $_POST["price"];} ; ?></td>
<td class="debt"><?php if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected){
if ($selected == 'everybody'){ echo $_POST["price"]/4;}
elseif ($selected == 'John' || 'Peter' || 'Ferrari'){ echo $_POST["price"]/2;}
elseif ($selected == 'John' && $selected == 'Peter') { echo $_POST["price"]/3;} ;
}}}?> </td></tr>
<td class="total"><?php if (isset($_POST['submit'])) { ;} ; ?></td></tr>
</table>
<button onClick="location.reload();location.href='secondpage.php'">ADD</button> <button>PAY</button></center>
and javascript
function ckChange(el) {
var ckName = document.getElementsByName(el.name);
if (el.checked) {
for (var i = 0; i < ckName.length; i++) {
ckName[i].disabled = ckName[i] !== el;
}
} else {
for (var i = 0; i < ckName.length; i++) {
ckName[i].disabled = false
}
}
}
$(function(){
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
});
When i try to get the answer of 2 checked checkboxes like
elseif ($selected == 'John' && $selected == 'Peter') { echo $_POST["price"]/3;}
it doesn't give me the right answer. I don't get the price divided by 3. For example: i chose the price 15 and under debt should be 15/3 = 5. Instead of 5 i get 7.5 7.5. Any solutions?
The problem not just in
elseif ($selected == 'Jacopo' && 'Denis' && 'Angus'){ echo $_POST["price"]/2;}
So first you want to know that this line must wrote like this.
elseif ($selected == 'Jacopo' || $selected == 'Denis' || $selected == 'Angus'){ echo $_POST["price"]/2;}
And Second you don't want to use another foreach. we want to make sure that the elements you're looking for inside the check_list array, So you can use in_array() function.
This is your final code.
<td class="debt"><?php
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])){
if (in_array('everybody', $_POST['check_list'])){ echo $_POST["price"]/4;}
elseif (in_array('Jacopo', $_POST['check_list']) && in_array('Denis', $_POST['check_list'])) { echo $_POST["price"]/3;}
elseif (in_array('Jacopo', $_POST['check_list']) || in_array('Denis', $_POST['check_list']) || in_array('Angus', $_POST['check_list'])){ echo $_POST["price"]/2;}
}
}
?></td>
I hope everything is clear and i hope i helped you.
I think you want it like this (correct me if not):
if "everybody" was checked, case 1
if ALL THREE (respectively TWO) boxes with names are checked, cases 2 or 3
any other combination will be ignored
In this case you must ensure, that $_POST['check_list'] has all the required items checked and nothing more. Please consider the following example:
// to play around with...
$_POST['check_list'] = ['everybody', 'Jacopo', 'Denis'];
$case1 = ['everybody'];
$case2 = ['Jacopo', 'Denis', 'Angus'];
$case3 = ['Jacopo', 'Denis'];
$result1 = array_intersect($_POST['check_list'], $case1);
$result2 = array_intersect($_POST['check_list'], $case2);
$result3 = array_intersect($_POST['check_list'], $case3);
if (count($case1) == count($result1)) {
echo 'case 1';
}
elseif (count($case2) == count($result2)) {
echo 'case 2';
}
elseif (count($case3) == count($result3)) {
echo 'case 3';
}
The array_intersect will compare all arrays to find things in common. Anything that is not in any of the other arrays will be removed. Set theory.
edit: fixed typos
I've build a function in javascript to show me a second submit but only after the first submit was clicked.
Edited - this is ex.php:
<form method="post" action = "ex.php">
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
inputSubmit = document.getElementById("submit");
function myFunction(){
inputSubmit.style.display = "block"; };
</script>
Updated:
I've edited in order to conclude the main problem.
So what I want is this:
a) The user has pressed the first submit button "search" then it will echo on the page "first search" and then show the second submit button "search_close" .
b)Then, if the user has pressed the second submit button it will show "second search".
When first Refreshing:
======
search (button)
======
if clicking the "search" button:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
if clicking the "find close results:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
second search (text)
This code doesn't do what I want. Why?
Updated - why the button find close results disappers after one second?
<?php
session_start();
$db=mysqli_connect("localhost","root","","travelersdb");
if(#$_SESSION["username"]){
?>
<?php
// function to connect and execute the query
function filterTable($query)
{
$connect=mysqli_connect("localhost","root","","travelersdb");
$filter_Result = mysqli_query($connect, $query) or die(mysqli_error($connect));
return $filter_Result;
}
$submit_value = 0;
if(isset($_POST['search']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$Age= $_POST['Age'];
$email = $_POST['email'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($Age)) {
$query.="AND age='$Age'";
}
if(!empty($email)) {
$query.=" AND email='$email'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 1;
}
///Make The search more wider, only for the fields that were in the post
else if(isset($_POST['search_close']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 2;
}
else {
$query = "SELECT * FROM `topics`";
$search_result = filterTable($query);
}
?>
<html>
<head>
<?php header('Content-Type: text/html; charset=utf-8'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Home Page</title>
<style>
.hidden {
display: none;
}
</style>
<script type="text/javascript">
function showHide()
{
var checkbox = document.getElementById("chk");
var hiddeninputs = document.getElementsByClassName("hidden");
for (var i=0; i != hiddeninputs.length; i++) {
if(checkbox.checked){
hiddeninputs[i].style.display = "block";
} else {
hiddeninputs[i].style.display = "none";
}
}
}
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
myFunction();
inputSubmit = document.getElementById("submit");
function myFunction(){
document.getElementById('submit').style.display = "block";
};
<?php } ?>
</script>
<body>
</body>
</head>
<?php include("header.php");?>
<center>
</br>
<button>Post</button>
</br>
<br/>
<h4>Simple Serach</h4>
<form action="" method="post">
<input type="text" name="Destination" placeholder="Destination" value=
"<?php if(isset($_POST['Destination']))
{echo htmlentities($_POST['Destination']);}?>" ></br>
<input type="text" name="TypeOfTravel" placeholder="Type Of Travel"
value=
"<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['TypeOfTravel']);}?>"
></br>
<input type="text" name="Age" placeholder="Age" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['Age']);}?>">
</br>
</br>
<!-- Advanced Search-->
<input type="checkbox" name="chkbox" id="chk" onclick="showHide()" />
<label for="chk"><b>Advanced search</b></label>
</br>
<input type ="text" name="email" placeholder="Email" class="hidden" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['email']);}?>">
<input type ="text" name="topic_name" placeholder="topic name" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['topic_name']);}?>">
<input type="text" name="StartingPoint" placeholder="Starting Point" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['StartingPoint']);}?>">
</br><br/>
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br><br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<br/>
<?php echo '<table border="1px">';?>
<td width="400px;" style="text-align:center;">
Name
</td>
<td width="400px;" style="text-align:center;">
Destination
</td>
<td width="400px;" style="text-align:center;">
Type Of Travel:
</td>
<td width="80px;" style="text-align: center;">
First Name
</td>
<td width="80px;" style="text-align: center;">
Age
</td>
<td width="400px;" style="text-align:center;">
profile picture
</td>
<td width="80px;" style="text-align: center;">
Creator
</td>
<td width="80px;" style="text-align: center;">
Date
</td>
</tr>
</center>
<?php
$sql = "Select * from `topics`";
$check = mysqli_query($db,$sql);
$rows = mysqli_num_rows($search_result);
if($rows != 0){
while ($row = mysqli_fetch_assoc($search_result)){
$id = $row['topic_id'];
echo "<tr>";
//echo "<td>".$row['topic_id']."</td>";
echo "<td style='text-align:center;'><a href='topic.php?id=$id'>".$row['topic_name']."</a></td>";
echo "<td>".$row['Destination']."</td>";
echo "<td>".$row['typeTravel']."</td>";
$sql_u = "Select * from users where username='".$row['topic_creator']."'";
$check_u = mysqli_query($db,$sql_u);
while ($row_u = mysqli_fetch_assoc($check_u))
{
$user_id = $row_u['id'];
$profile_pic = $row_u['profile_pic'];
$firstname = $row_u['firstname'];
$age = $row_u['age'];
echo "<td>".$firstname."</td>";
echo "<td>".$age."</td>";
echo "<td><img src='".$profile_pic."' width='10%' height='10%' alt='me'></td>";
echo "<td><a href='profile.php?id=$user_id'>".$row['topic_creator']."</a></td>";
}
$get_date = $row['date'];
echo "<td>".$row['date']."</td>";
echo "</tr>";
}
}else {
echo "No topics found";
}
echo "</table>";
if (#$_GET['action']=="logout")
{
session_destroy();
header('location:login.php');
}
}else
{
echo "You must be logged in.";
echo "<a href ='login.php'>Click here to login</a>";
}
?>
</br>
</br>
<body>
</body>
</html>
you need to set type button cause when you set type submit then form automatically submit so show second not show but it work.
<form method="post" action = "">
<input type="submit" id="button" name="search" value="Search" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
$submit_value = 0;
if(isset($_POST['search']))
{
echo "first search";
$submit_value = 1;
}
else if(isset($_POST['search_close']))
{
echo "first search";
echo '<br>';
echo "second search";
$submit_value = 2;
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
document.getElementById('submit').style.display = "block";
<?php } ?>
</script>
check this code
I have cleaned up your code, but the issue of having two submit buttons still persists. Even if the clicking of the first button causes the second to show, the first button will cause the page to reload with the results from the form's action resource. In this example, I have cancelled the form's submit event to show that the display of the second button works.
In the end, I think you are going about this all wrong. I think you should be making AJAX calls to your server-side resource and injecting the results of that call into your page - - no forms and no submits.
// Don't forget to add "var" to your variable declarations, otherwise the variables
// become global!
var sub1 = document.getElementById("btnSub1");
var sub2 = document.getElementById("btnSub2");
// Set up the event handler for the first button
sub1.addEventListener("click", myFunction);
function myFunction(e){
// Adjust classes, not individual styles
sub2.classList.remove("hidden");
// Cancel the native event and stop bubbling
e.preventDefault();
e.stopPropagation();
};
.hidden { display:none; }
<form>
<!-- Submit buttons don't get a name attriute unless you expect their value to be submitted
along with all the other form data. Inline styles should be avoided and internal style
sheets used instead. And, inline JavaScript event attributes (onclick, etc.) should not
be used. -->
<input type="submit" id="btnSub1" name="search" value="Search" >
<br>
<input type="submit" id="btnSub2" class="hidden" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>
I am working on a web site which displays some data that is retrieved from a database using php. Now, there are also other chekcboxes, which are included in a form. Based on the user input on these checkboxes, i wanted the div displaying the data to reload. For example, after a user checks one of the boxes and clicks apply, the div displaying should recompute the results. I realise that the form data must be passed onto an ajax function. Which would convert this form data into a json object and send it across to a php file. The php file can then access the form variables using $_POST['var']. I hope i have got the theory correct. Nevertheless, i have a number of problems during execution.
Firstly, the php code that deals with the form variables in on the same page as the form. I want to know how to direct the form data from the ajax function to this code.
Secondly, the ajax function is getting executed alright, the form is getting submitted, the page isn't reloading (as desired) but however, I am not able to access the submitted variables in the php code.
Here is my code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#filter_form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>
<div style="float: left;margin-left: -175px;" class="box2">
<h2>Filter by :</h2>
<form id="filter_form" name="filter_form" href="#">
<!--<form id="filter_form" name="filter_form" action="<?php echo $_SERVER['PHP_SELF'];?>" method ="post" href="#">-->
<h3>Location</h3>
<?php
//Get all the distinct values for filter. For example, Get all the locations available, display them in a container. Similarly for the party type as well. Connect to to the database once, get all these values,
//store them in arrays and use the arrays to display on screen.
$query = "Select LOCATION, PARTY_TYPE, GENRE, HAPPY_HOURS, OUTDOOR_ROOFTOP from venue_list order by HAPPY_HOURS";
$result = mysqli_query($con,$query);
$filter_array = array(5);
for($i=0; $i<5; $i++){
$filter_array[$i] = array();
}
while($row = mysqli_fetch_array($result)){
array_push($filter_array[0],$row['LOCATION']);
array_push($filter_array[1],$row['PARTY_TYPE']);
array_push($filter_array[2],$row['GENRE']);
array_push($filter_array[3],$row['HAPPY_HOURS']);
array_push($filter_array[4],$row['OUTDOOR_ROOFTOP']);
}
for($i=0; $i<5; $i++){
$filter_array[$i] = array_unique($filter_array[$i]);
}
?>
<ul>
<?php
foreach($filter_array[0] as $location){
?>
<li>
<input type="checkbox" id="f1" name="location[]" value="<?php echo $location?>" <?php if (isset($_POST['location'])){echo (in_array($location,$_POST['location']) ? 'checked' : '');}?>/>
<label for="f1"><?php echo $location?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Party Type</h3>
<ul>
<?php
foreach($filter_array[1] as $party_type){
?>
<li>
<input type="checkbox" id="f2" name="party_type[]" value="<?php echo $party_type?>" <?php if (isset($_POST['party_type'])){echo (in_array($party_type,$_POST['party_type']) ? 'checked' : '');}?>/>
<label for="f2"><?php echo $party_type?></label>
</li>
<?php
}
?>
</ul>
<br><h3>Genre</h3>
<ul>
<?php
foreach($filter_array[2] as $genre){
?>
<li>
<input type="checkbox" id="f3" name="genre[]" value="<?php echo $genre?>" <?php if (isset($_POST['genre'])){echo (in_array($genre,$_POST['genre']) ? 'checked' : '');}?>/>
<label for="f3"><?php echo $genre?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Happy Hours</h3>
<ul>
<?php
foreach($filter_array[3] as $happy_hours){
?>
<li>
<input type="checkbox" id="f4" name="happy_hours[]" value="<?php if($happy_hours){ echo $happy_hours;} else {echo "Dont Bother";} ?>" <?php if (isset($_POST['happy_hours'])){echo (in_array($happy_hours,$_POST['happy_hours']) ? 'checked' : '');}?>/>
<label for="f4"><?php echo $happy_hours?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Outdoor/Rooftop</h3>
<ul>
<?php
foreach($filter_array[4] as $outdoor_rooftop){
?>
<li>
<input type="checkbox" id="f5" name="outdoor_rooftop[]" value="<?php echo $outdoor_rooftop?>" <?php if (isset($_POST['outdoor_rooftop'])){echo (in_array($location,$_POST['outdoor_rooftop']) ? 'checked' : '');}?>/>
<label for="f5"><?php echo $outdoor_rooftop?></label>
</li>
<?php
$i=$i+1;
}
?>
</ul>
<br><br><br>
<div id="ContactForm" action="#">
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
</div>
<!--
<h2>Sort by :</h2>
<input type="radio" id="s1" name="sort" value="Name" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Name')?'checked':'';}?>/>
<label for="f1"><?php echo 'Name'?></label>
<input type="radio" id="s1" name="sort" value="Location" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Location')?'checked':'';}?>/>
<label for="f1"><?php echo 'Location'?></label>
<br><br><br>
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
-->
</form>
</div>
<div class="wrapper">
<h2>Venues</h2>
<br>
<div class="clist" id="clublist" href="#">
<?php
?>
<table id = "venue_list">
<tbody>
<?php
//Functions
//This function builds the query as every filter attribute is passed onto it.
function query_builder($var_name){
$append = strtoupper($var_name)." in (";
$i=0;
foreach($_POST[$var_name] as $array){
$append = $append."'{$array}'";
$i=$i+1;
if($i < count($_POST[$var_name])){
$append = $append.",";
}
else{
$append=$append.")";
}
}
return $append;
}
//We first need to check if the filter was set in the previous page. If yes, then the query needs to be built with a 'where'. If not the query will just display all values.
//We also need to check if order by is required. If yes, we will apply the corresponding sort, else we will just sort on the basis of location.
//The below 2 variables do the same.
$filter_set = 0;
$filter_variables = array('location','party_type','genre','happy_hours','outdoor_rooftop');
$map_array = array();
if(isset($_POST['location'])){
$filter_set = 1;
}
if(isset($_POST['party_type'])){
$filter_set = 1;
}
if(isset($_POST['genre'])){
$filter_set = 1;
}
if(isset($_POST['happy_hours'])){
$filter_set = 1;
}
if(isset($_POST['outdoor_rooftop'])){
$filter_set = 1;
}
if($filter_set == 1){
$query = "Select * from venue_list where ";
$append_query=array(5);
$j=0;
foreach($filter_variables as $var){
if(isset($_POST[$var])){
$append_query[$j] = query_builder($var);
$j=$j+1;
}
}
$h=0;
//Once all the individual where clauses are built, they are appended to the main query. Until then, they are stored in an array from which they are
//sequentially accessed.
foreach($append_query as $append){
$query=$query.$append;
$h=$h+1;
if($h < $j){
$query=$query." AND ";
}
}
}
else{
$query = "Select * from venue_list";
}
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$name = $row['NAME'];
$img = $row['IMAGE_SRC'];
$addr = $row['ADDRESS'];
$location = $row['LOCATION'];
echo "<script type='text/javascript'>map_function('{$addr}','{$name}','{$img}');</script>";
?>
<tr>
<td>
<img src="<?php echo $img.".jpg"?>" height="100" width="100">
</td>
<td>
<?php echo $name?>
</td>
<td style="display:none;">
<?php echo $location?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<br>
</div>
All the 3 components are part of index.php. Kindly notify me if the code is unreadable or inconvenient I will edit it. Awaiting a solution. Thank you.
in this case change your javascript code to
var submiting = false;
function submitmyforum()
{
if ( submiting == false )
{
submiting = true;
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
submiting = false;
}
});
}else
{
alert("Still working ..");
}
}
and change the form submit button to
<input name="filter_button" type="button" onclick="submitmyforum();" value="Apply" id="filter_button" class="button"/>
don't forget to change submit button type="submit" to type="button"