save multi checkbox by id - javascript

I am working with live checkbox, so when I need to put ON(1) or OFF(0) one checkbox immediately the checkbox update the value in the DB and all is ok...but now I am working with live checkbox in a user list(which I already have right now 100 users)...so the problem is when I try to put someone a ban, the checkbox just only works with the last one and not in the others users... can you please help me?
Here is the form:
<form class="form-horizontal" method="post" name="ban" id="ban">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<?php if ($row['banned'] == '1') {
echo '<input type="checkbox" name="banned" data-no-uniform="true" class="iphone-toggle" value="on" checked>';
} else {
echo '<input type="checkbox" name="banned" data-no-uniform="true" class="iphone-toggle" value="off" >';
} ?>
</form>
<div id="gif" style="display:none;" align="center"><img src="img/ajax-loaders/ajax-loader-1.gif" /></div>
Here the JS:
$("#ban").click(function(){
$.ajax({
type:"POST",
url:"includes/ban.php?ts=" + new Date().getTime(),
dataType:"text",
data:$(this).serialize(),
beforeSend:function(){
$("#gif").show();
},
success:function(response){
$("#gif").hide();
}
})
return false;
});
And this is the code to DB:
<?php
include('con.php');
if($_POST['banned']==on) {
try{
$id = $_POST['id'];
$banned = '0';
$sql = "UPDATE BANS SET
banned = :banned
WHERE id= :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':banned', $banned, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-success fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
the ban is off!.
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
} else {
try{
$id = $_POST['id'];
$banned = '1';
$sql = "UPDATE BANS SET
banned = :banned
WHERE id= :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':banned', $banned, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-danger fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
the ban is on!
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
$dbh = null;
?>

The reason only the last one is getting submitted is because you can't assign the same id to multiple elements.
Change: <form class="form-horizontal" method="post" name="ban" id="ban">
To: <form class="form-horizontal ban" method="post">
Then update your jQuery selector to $("form.ban")
Finally, in your PHP: if($_POST['banned']==on) {
Should be: if($_POST['banned']=='on') {
Edit: As a side-note, the same problem will affect the AJAX loader GIF, assuming again that you have an AJAX loader in each row, but that's outside the scope of this question.

Related

Passing Hidden ID value to another page using javascript php

I am trying to pass hidden value from page to another page and it work fine only for first record however for other records it's showing error
Here is the code:
$sql = "SELECT id,jdes,title FROM job";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<input type="hidden" id="hidden_user_id" value="<?php echo $row["id"] ?>">
<h3><?php echo $row["title"] ?>:</h3>
<p class="lead">
<?php echo $row["jdes"] ?>
</p>
<button type="button" id="requestthis" class="btn btn-primary">
Request
</button>
<?php
}
} else {
echo "Nothing to display Yet";
}
?>
jobs-inner.php
<?php
echo $_GET['hidden_id'];
?>
Javascript:-
$(function() { //ready function
$('#requestthis').on('click', function(e){ //click event
e.preventDefault();
var hidden_id = $('#hidden_user_id').val();
var url = "jobs-inner.php?hidden_id="+hidden_id;
window.location.replace(url);
})
})
Error:-
Undefined index: hidden_id in C:\wamp64\www\project\jobs-inner.php on line 3
It might be a simple problem but I am a beginner and I can't figure it out.
Your value is unique but the id isn't. Make the id of the input unique something like below.
<input type="hidden" id="hidden_user_<?php echo $row["id"] ?>" value="<?php echo $row["id"] ?>">
but you would have to do a count on code below to make it display base on how many rows you have.
<?php
echo $_GET['hidden_id'];
?>
Without JavaScript
$sql = "SELECT id,jdes,title FROM job";
$result = $conn->query($sql);
$count = 1;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<input type="hidden" id="hidden_user_<?php echo $count ?>" value="<?php echo $row["id"] ?>">
<h3><?php echo $row["title"] ?>:</h3>
<p class="lead"><?php echo $row["jdes"] ?></p>
<form id="<?php echo $count ?>" action="jobs-inner.php?hidden_id=<?php echo $row["id"] ?>" method="post">
<input type="submit" vaule="Request">
</form>
<?php
$count++;
}
} else {
echo "Nothing to display Yet";
}
?>

PHP forms through loop doesn't send specific session against checked radio button

I am working on an e-testing system in which when a candidate login the test for which he/she was register will be shown to him/her.
I am getting the specific test through session to show the questions containing in that test. This was successfully done with the help of some "if" checks and two while loops(1 for questions and 2nd for answers against that question) having the form of radio buttons for selecting an answer.
Now each time when loop execute it create a form for single question and its answer, that way for multiple questions it results in multiple.
I am getting the checked radio buttons through ajax and posting it to another php file but I need a question id of checked answer as well to be passed to the 2nd php file
I used session but it only get the id of 1st checked and not for the others.
The 2nd php file name is answers.php for the time being i just want to post and get all values and session in answers.php file.
the main problem is with $_SESSION ['qid'] = $id; session
Note: i have used unset and destroy session to free the session and tried to re start it but i am field to do so..
<?php
include ("connection.php");
// $mysql_row = '';
$query_run = null;
$test = $_SESSION ['id'];
var_dump ( $_SESSION ['id'] );
$query1 = "SELECT * FROM question where testid = '" . $_SESSION ['id'] . "'";
if ($query_run = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
print "No result";
} else {
// echo'<form action="ss.php" method="post">';
while ( $mysql_row = mysql_fetch_assoc ( $query_run ) ) {
$id = $mysql_row ['qid'];
$_SESSION ['qid'] = $id;
echo ' <div class="panel-heading" style="background: black; font-weight:bold;">Question </div>';
$data = $mysql_row ['questions'];
?>
<form>
<br>
<div class=" form-control well well-sm">
<?php echo'<div style="font-weight:bold;"> Q: '.$data.' </div> '; ?>
<br>
</div>
<?php
$query1 = "SELECT * FROM `answer` where id='" . $id . "'";
if ($query_run1 = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
} else {
while ( $mysql_row1 = mysql_fetch_assoc ( $query_run1 ) ) {
$data1 = $mysql_row1 ['ans1'];
$data2 = $mysql_row1 ['ans2'];
$data3 = $mysql_row1 ['ans3'];
$data4 = $mysql_row1 ['ans4'];
echo "\n";
?>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option1</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data1' name='opt1' onclick='OnChangeRadio (this)'> $data1<br />";
?>
<br>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option2</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data2' name='opt1' onclick='OnChangeRadio (this)'> $data2<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option3</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data3' name='opt1' onclick='OnChangeRadio (this)'> $data3<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option4</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data4' name='opt1' onclick='OnChangeRadio (this)'> $data4<br />";
// echo'</form>';
?>
</div>
<?php
echo '</form>';
}
}
}
// $view_id1 = $view_id;
// echo $view_id1;
}
}
} else {
print mysql_error ();
}
// unset($_SESSION['qid']);
?>
connection.php
<?php
session_start ();
if (! $_SESSION ['user']) {
header ( "Location: index.php" );
// redirect to main page to secure the welcome
// page without login access.
}

ajax delete post asynchronously - php

I'm trying to create a add/delete/edit post system using php for a website. I have the add working, so when the user enters in information it gets added to the database and then asynchronously gets added onto the page using ajax. I want a similar function that deletes asynchronously as well. Right now, when I click delete, only the oldest post gets deleted AFTER refreshing the page. It does not delete the post as soon as I click the delete button which is my goal. This is what I have so far. The home.php is where my form is that collects the information and also prints out the information from the database. handledelete.php is where the deleting is handled.
home.php
<script>
$(function() {
$('#deleteButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#show_entries").append(html);
}
});
});
});
</script>
<div id="entry">
<form method="GET" action="handle_insert.php">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="activity" id="activity" placeholder="Activity" required /></td>
</tr>
<tr>
<td><input type="text" name="duration" id="duration" placeholder="Duration (hours)" required /></td>
</tr>
<tr>
<td><input type="text" name="date" id="date_" placeholder="Date (YYYY-MM-DD)" required /></td>
</tr>
<tr>
<td><button type="submit" name="submitButton" id="submitButton">Add input</button></td>
</tr>
</table>
</form>
</div>
<!-- shows the previous entries and adds on new entries-->
<div id="show_entries">
<?php
$userID = $_SESSION["user"];
$link = mysqli_connect('localhost', 'oviya', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '<button type="submit" name="deleteButton" data-id='.$entry_id.' id= "deleteButton">Delete</button>';
//echo '<button type="submit" name="editButton" data-id='.$entry_id.' id="editButton">Edit</button>';
echo '</div>';
}
?>
</div>
handle_delete.php
session_start();
$user = 'oviya';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["entry_id"])){
$entry_id = mysqli_real_escape_string($link, $_GET["entry_id"]);
$sql = "DELETE FROM dataTable WHERE entry_id = '$entry_id'";
$result = mysqli_query($link, $sql);
die();
mysqli_close($link);
}
This line is the problem. It would add elements if your AJAX call were returning HTML, which it isn't:
$("#show_entries").append(html);
Instead, you want to remove the deleted element, which you can reference directly and remove from the DOM:
$('#deleteButton').click(function(event) {
event.preventDefault();
// Get a reference to the whole row element.
var row = $(this).parent();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
success: function(html){
// Remove the row
row.remove();
}
});
});

How to differentiate each submit button in a foreach loop

My code:
<?php
require_once 'core/init.php';
if($result = $db->query ("SELECT * from countries")) {
if($count = $result->num_rows) {
$rows = $result->fetch_all(MYSQLI_ASSOC);
}
}
?>
<div class="region">
<h1>Europe</h1>
<ul class="country" style ="list-style-type:none">
<?php foreach ($rows as $key => $row) { ?>
<li>
<a href=""=<?php echo $row['country_id']; ?>">
<a href=""=<?php echo $row['region_id']; ?>">
<?php echo $row['country_name']; ?></a> <br>
<?php
if (isset($_FILES['country_img']) === true) {
if (empty($_FILES['country_img']['name']) === true) {
echo 'please choose a file!';
print_r ($_POST);
} else {
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['country_img']['name'];
$file_extn = end(explode('.', $file_name));
$file_temp = $_FILES['country_img']['tmp_name'];
if (in_array($file_extn, $allowed) ===true) {
if ($_POST['id'] = $_POST['id']) {
addcountryimage($row['country_id'], $file_temp, $file_extn);
}
header ('Location: tes2.php');
break;
}else {
echo 'Incorrect file type. Allowed: ';
echo implode (', ', $allowed);
}
}
}
if (empty($row['country_img'] === false)) {
echo '<img src="', $row['country_img'], '" alt="', $row['country_name'], '\'s Image">';
}
?>
<p> <?php echo $row['country_bio']; ?></p>
<?php
global $session_user_id;
if (is_admin($session_user_id) === true) { ?>
<form action="" method="POST" name="" enctype="multipart/form-data">
<input type="hidden" name="id" id="hidden_id">
<input type="file" name="country_img"> <input type="submit" onclick="document.getElementById('hidden_id').value=$row['country_id']" />
</form>
<?php } ?>
<p> Tour to <?php echo $row['country_name']; ?></p>
</li>
<?php } ?>
</ul>
<h3> More European Country </h3>
</div>
Everything above works, except the fact that it can't differentiate between each submit button. For example, when I update the image on the 5th forms it will always update the 1st form. How can I do this?
The origin of your issue is using multiple id attributes with the same value in your JavaScript events, this is regarded wrong, every element id must be unique, beside this, onclick event with submit typed inputs of form is not working properly.
Add an incremental counter to your loop and then use to distinguish each form hidden element id.
<?php $i = 0;?>
<?php foreach ($rows as $key => $row) { ?>
....
<input type="hidden" name="id" id="hidden_id_<?php echo $i;?>">
....
<input type="submit" onclick="document.getElementById('hidden_id_<?php echo $i;?>').value=$row['country_id']" />
<?php
$i++;
} ?>
Another note, I think that onclick event does not works fine with submit type inputs, so I suggest to replace it with onsubmit event in the form itself as:
<form action="" method="POST" name="" enctype="multipart/form-data" onsubmit="document.getElementById('hidden_id_<?php echo $i;?>').value=$row['country_id']">

update multiple checkbox with javascript and ajax

I am working with multiple checkboxes with javascript and ajax. When the checkbox is clicked the javascript send with ajax the values to trata.php (these values: checked if is true or false and the id of that checkbox)...but the id always show me undefined....can you guide me, please.
Here is the JS:
$("div.feature").click(function() {
var checked = $(this).is(':checked');
var Id = $(this).attr('id');
var data = "Cara=" + checked + "&Id=" + Id;
$.ajax({
type: "POST",
url: "trata.php?ts=" + new Date().getTime(),
data: data,
cache: false,
beforeSend: function() {
$("#tr").show();
$("#t").empty();
},
success: function(response) {
$("#tr").hide();
$("#t").append(response);
}
})
return false;
});
$("div.feature1").click(function() {
var checked = $(this).is(':checked');
var Id = $(this).attr('id');
var data = "Pieza=" + checked + "&Id=" + Id;
$.ajax({
type: "POST",
url: "trata.php?ts=" + new Date().getTime(),
data: data,
cache: false,
beforeSend: function() {
$("#tr").show();
$("#t").empty();
},
success: function(response) {
$("#tr").hide();
$("#t").append(response);
}
})
return false;
});
In page this is the code:
<table>
<tr>
<td>
<div class="feature" align="center">
<input type="text" value="<?php echo $row['Id'] ?>" name="Id" id="Id" /> <!-- in this Id the value is 1 -->
<input type="checkbox" data-no-uniform="true" class="iphone-toggle" <?php if ($row[ 'Cara']=='1' ) {echo 'name="Cara" value="on" checked="checked"';} else { echo 'name="Cara" value="off"'; } ?>>
</div>
<div id="tr" style="display:none;" align="center"><img src="img/ajax-loaders/ajax-loader-1.gif" />
</div>
<div id="t"></div>
</td>
<td>
<div class="feature1" align="center">
<input type="text" value="<?php echo $row['Id']; ?>" name="Id" id="Id" /> <!-- in this Id the value is 2 -->
<input type="checkbox" data-no-uniform="true" class="iphone-toggle" <?php if ($row[ 'Pieza']=='1' ) {echo 'name="Pieza" value="on" checked="checked"';} else { echo 'name="Pieza" value="off"'; } ?>>
</div>
<div id="tr" style="display:none;" align="center"><img src="img/ajax-loaders/ajax-loader-1.gif" />
</div>
<div id="t"></div>
</td>
</tr>
</table>
In trata.php //MySQL + PDO
<?php
include('conn.php');
if(isset($_POST['Cara'])) {
try{
$Id = $_POST['Id'];
if ($_POST['Cara'] == false) {
global $Cara;
$Cara = 0;
} else if ($_POST['Cara'] == true) {
global $Cara;
$Cara = 1;
};
$sql = "UPDATE Trata SET
Cara = :Cara
WHERE Id= :Id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':Cara', $Cara, PDO::PARAM_STR);
$stmt->bindParam(':Id', $Id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-primary fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
ok.
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
} if(isset($_POST['Pieza'])) {
try{
$Id = $_POST['Id'];
if ($_POST['Pieza'] == false) {
global $Pieza;
$Pieza = 0;
} else if ($_POST['Pieza'] == true) {
global $Pieza;
$Pieza = 1;
};
$sql = "UPDATE Trata SET
Pieza = :Pieza
WHERE Id= :Id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':Pieza', $Pieza, PDO::PARAM_STR);
$stmt->bindParam(':Id', $Id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-primary fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
ok.
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
$dbh = null;
?>
Another thing is the loading ajax is show me only in the first td and I have 8 td files..
div.feature and div.feature1 do not have ids. That is why $(this).attr('id') is returning undefined. Try this:
$('div.feature input:checkbox').click(function(){
var Id = $(this).attr('id');
});

Categories

Resources