I have input field checkboxes,
<input value="1" name="rubric_chkbox[]" type="checkbox" class="checkbox" />
<input value="2" name="rubric_chkbox[]" type="checkbox" class="checkbox" />
<input value="3" name="rubric_chkbox[]" type="checkbox" class="checkbox" />
My problem is that in my foreach loop insert query if I checked all the checkbox,
It will just insert value 1 and 2 in my database it ignores the value 3.
I'm using jquery and ajax to get the checkboxes.
var rubricChkbox = new Array();
$(".rubricChkbox:checked").each(function() {
rubricChkbox.push($(this).val());
});
console.log(rubricChkbox);
$.ajax({
url: "Queries/save.php",
type: "POST",
data: {
"rubricChkbox":rubricChkbox
},
success: function(yey){
console.log(yey);
alert(yey);
}
});
});
});
And this is my save.php,
if (isset($_POST['rubricChkbox']) || isset($_POST['uncheked']) || isset($_POST['user_id'])) {
$rubric_value = $_POST['rubricChkbox'];
$IDuser = $_POST['user_id'];
foreach($rubric_value as $rubric_check) {
$sql_check = "SELECT raw_selected_rubric FROM rubric_selected INNER JOIN cmat_composition ON rubric_selected.ID_cmat = cmat_composition.ID_cmat WHERE rubric_selected.ID_users = '$IDuser' AND raw_selected_rubric = '$rubric_check'
AND rubric_selected.Saved = '1'";
$result_check = mysqli_query($conn,$sql_check);
if (mysqli_num_rows($result_check) <= 0){
$sql_raw = "INSERT INTO rubric_selected (raw_selected_rubric, Saved, ID_users)
VALUES ('$rubric_check', '1', '$IDuser')";
mysqli_query($conn, $sql_raw);
}
}
What did I missed out? Thank you.
The best advice for you is that if something doesn't work the way you want, you should examine what happens at each step until you find the problem. This doesn't only apply to this question, but to any programming problem (and many others).
In this case
Is the data sent from the browser correct? You already have the statement console.log(rubricChkbox);. Did you check that value? Why didn't you include it in the the question?
Does the correct data arrive at the PHP script? Use something like print_r ($_POST);.
The SQL INSERT depends on the result of a SQL SELECT. Did you check that this condition is true, because otherwise your code wont even try to insert.
Does the INSERT statement return some error?
Related
When I click on select all, I get all the checkboxes checked and disabled, and when I uncheck select all, all checkboxes become unchecked and normal again.
Then I tried to do the exact same thing with retrieving data from the db with a loop and I can select all, but when I deselect 'select all' it will all get unchecked but disabled.. how can I "undisable" it?
Demo for simple html version: http://jsfiddle.net/k6R7g/11/
The php version that doesn't work:
<?php
echo '<input type="checkbox" name="category[]" class="category_all" value="0">All';
if ( $db_conn = connDB() ){
$sql_categories = "SELECT * FROM cat";
$rs = getRows($sql_categories, $db_conn);
foreach ($rs as $row) {
echo '<input type="checkbox" class="categories_list" name="category[]" value="'.$row['cat_id'].'">'.$row['cat_name'].'';
}
$db_conn = null;
}
?>
The rows echo fine in the dropdown, just the deselection part of 'select all' isn't working. What am I doing wrong?
Please change:
$(".categories_list").prop("checked", is_checked).attr("disabled", is_checked);
To:
$(".categories_list").prop("checked", is_checked).prop("disabled", is_checked);
As you mentioned, noraml jquery it is working fine. Hopefully this will work in php. Update your jquery block like below.
$(function() {
$("input[type=checkbox]").change(function() {
if ($(this).hasClass("category_all")) {
var is_checked = $(this).is(":checked");
if(is_checked){
$(".categories_list").prop("checked", is_checked).attr("disabled","true");
}
else
{
$(".categories_list").prop("checked", is_checked).removeAttr("disabled");
}
}
});
});
Becuase in Normal checkbox, if you give disabled="true" or disabled="false" will give the same output.
Im scratching my head once again and need your help.
What I have is a form that submits to a second page, with sessions enabled, i am storing the name value 2 fields on the form and setting their value names in the session so that if a user returns to a page their Username will already be populated in the text field. I have this working ok ..
The second page i am storing
$_SESSION['captured_by'] = $_POST['captured_by'];
$_SESSION['prid'] = $_POST['prid'];
HOWEVER..
Where i am stuck is getting a select option that is populated from a query to have the same functionality, so that when a user returns to the page, the selected option which has been saved in the session will keep that selection in the box rather than having to select it again.
Here is what i have as follows:
Form Page:
This does work and does return the captured_by text when i return to the page
<fieldset><legend>Lesson Added By *</legend>
<p class="multiple">(Required - Logon ID)</p>
<input name="captured_by" maxlength="12" id="searchfield" type="text" value="<?php
if(isset($_SESSION['captured_by'])){print stripslashes($_SESSION['captured_by']);}
else{print " ";} ?>">
</fieldset>
The problem code is this
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'">'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
I need to edit this last section so that it picks up the previously selected option value from the stored session value.
Hope someone can help?
Many Thanks.
Tazzy
Try this,
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'"'. ((isset($_SESSION['prid']) && !empty($_SESSION['prid']) && ($_SESSION['prid'] == $row['project_id'])) ? 'selected="selected"' : '') .'>'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
You could simply use ajax when someone change the selection.
$('select#searchfield').change(function(){
$.ajax({
type: 'GET',
url: 'changeSession.php', // This is the url that will be requested
data: {prid: $('select#searchfield').val()},
success: function(html){
// nothing really happens because you simply update your session
},
dataType: 'html'
});
});
Then in changeSession.php
if(isset($_GET['projectId']{
$_SESSION['captured_by'] = $_POST['prid'];
}
That should do the job. You then add a condition when the form is generated and you add selected='selected' if $_SESSION['prid'] is not empty.
I am creating an admin panel for a project that I am working on. It will list a bunch of entries in a table and each row will have a checkbox in it. This checkbox will be used to activate an entry to be displayed on the website.
I am setting the id and name of the checkbox with data from the MySQL database. For example..
<input type="checkbox" class="active" name="active<?php echo $id; ?>" id="active<?php echo $id; ?>" <?php if ($active == 1): ?>checked="checked"<?php endif; ?> value="<?php echo $id; ?>">
For the entry with ID of 5 it will look like this..
<input type="checkbox" class="active" name="active5" id="active5" checked="checked" value="5">
I need to set this up so that when you check a box or uncheck it that it updates the "active" value in the database. How do I grab the value of each checkbox, when clicked, and send that value to the MySQL database. I can do this easily if I know the checkboxes name beforehand, but since the name is partly generated from the database I'm not sure how to write the code to determine which entry gets the active value.
Here is my jQuery..
$("input.active").click(function() {
// store the values from the form checkbox box, then send via ajax below
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $(this).attr('value');
console.log(check_active);
console.log(check_id);
$.ajax({
type: "POST",
url: "http://nowfoods.marketspacecom.com/nextstep/ajax.php",
data: {id: check_id, active: check_active},
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return true;
});
Here is the PHP..
<?php
include("dbinfo.inc.php");
mysql_connect($server,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// CLIENT INFORMATION
$active = mysql_real_escape_string($_POST['active']);
$id = mysql_real_escape_string($_POST['id']);
$addEntry = "UPDATE entries SET active = '$active' WHERE id = '$id'";
mysql_query($addEntry) or die(mysql_error());
mysql_close();
?>
You could add a class to the input and set the value to the id instead:
<input class="active" type="checkbox" name="active5" id="active5" value="5" checked="checked">
Then, change your jQuery:
$("input.active").click(function() {
// store the values from the form checkbox box, then send via ajax below
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $(this).attr('value');
$.ajax({
type: "POST",
url: "http://nowfoods.marketspacecom.com/nextstep/ajax.php",
data: {id: check_id, active: check_active}
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return true;
});
As for PHP:
<?php
include("dbinfo.inc.php");
mysql_connect($server,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// CLIENT INFORMATION
$active = mysql_real_escape_string($_POST['active']);
$id = mysql_real_escape_string($_POST['id']);
// WHERE id=16 is just for testing purposes. Need to dynamically find which checkbox was checked and use that info to tell the query which ID to update.
$addEntry = "UPDATE entries SET active = '$active' WHERE id = '$id'";
mysql_query($addEntry) or die(mysql_error());
mysql_close();
?>
This should be what you're looking for. There may be some minor syntax issues, because I'm writing this off the top of my head, but I hope you get the general idea. :-)
This is wrong:
var active = $('#active').attr('value');
You need to check the clicked element and you have to check whether it is checked or not (the value doesn't really matter that much unless you use it to pass the ID):
var active = $(this).is(':checked'); // the checkbox is checked (boolean)
You can set it to an integer value like:
var active = $(this).is(':checked') ? 1 : 0;
Which is short for:
if ($(this).is(':checked')) {
var active = 1;
} else {
var active = 0;
}
And in php you need process you user input correctly:
$active = (int) $_POST['active'];
Edit: It seems you have a space that should not be there in your edited code, does it work when you set:
...
data: {"active=": check_active, "id": check_id},
...
Also, as both values are integers / should be integers, there is no real use escaping them for the database using a string function, you should test for integers or at the very least cast them to integers:
// CLIENT INFORMATION
$active = (int) $_POST['active'];
$id = (int) $_POST['id'];
I have the following code:
<?php
$allform = $_POST['allform'];
parse_str($allform, $output);
$allquery = "SELECT * FROM wp_users";
$names = array();
$allresult = mysql_query($allquery) or die(mysql_error()); ?>
...
<?php
while ($rows = mysql_fetch_array($allresult)) {
$names[] = $rows['user_email'];
}
?>
The allform variable is a jQuery serialize string:
var allform = $('form#all').serialize();
Basically, I want to put the values from the form in the front end into a mysql select query in the back end.
The form is a bunch of checkboxes so the idea is that the SELECT something will have different number of values depending on what the user checks. Any ideas?
Thanks
The best thing to do could be something like this. Your checkboxes should be like this
<input type="checkbox" name="checkboxes[]" value="cream" />
<input type="checkbox" name="checkboxes[]" value="choco" />
<input type="checkbox" name="checkboxes[]" value="lime" />
server side you receive an array
$flavours = $_POST["checkboxes"];
$sql = "SELECT ".implode(',', $flavours)." FROM FLAVOURTABLE";
I'm trying to add tick boxes and when the boxes are ticked a value adds up (a variable) that variable is then added into the database along with each checkbox once the form is submitted, I've been trying to modifiy this code but cant figure out how to not use the parseInt() function and output a single variable that I can then add into the database/Email reply to the customer. I'm really stuck and would appreciate some help.
(the options are suppose to actually be (deodoriser,carpet,carpetrepair,furniture,tabs,urine but im using demo options for now below in the insert staement they are the correct names)
This is my HTML:
<p><input type="checkbox" name="extras[]" value="option1" rel="11">furniture</p>
<p><input type="checkbox" name="extras[]"" value="option2" rel="12">tabs</p>
<p><input type="checkbox" name="extras[]" value="option3" rel="13">urine</p>
<p><input type="checkbox" name="extras[]" value="option4" rel="30">couch</p>
<p><input type="checkbox" name="extras[]" value="option5" rel="20">steam</p>
<span id="output"></span>
This is my javascript function
$(document).ready(function() {
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
This is my email reply/datbase inserting at the moment
$idextra=$_POST['extras'];
$arr_num=count($idextra);
$i=0;
while ($i < $arr_num)
{
$q="INSERT INTO bs_reservations (dateCreated, name, email, phone, comments,status,eventID, qty,dropoff,deodoriser,carpet,carpetrepair,furniture,tabs,urine) VALUES (NOW(),'".$name."','".$email."','".$phone."','".$comments."','2','".$eventID."','".$qty."','".$dropoff."','{$idextra[1]}','{$idextra[2]}','{$idextra[3]}','{$idextra[4]}','{$idextra[5]}','{$idextra[6]}')";
$res=mysql_query($qu) or die('ERROR INSERTING: '.mysql_error());
$i++;
}
Thanks heaps for any advice/help in coding this. I know its a big question but I feel it will help a lot of people in the future.
$res=mysql_query($qu)
change that to
$res=mysql_query($q)
and probably this too
name="extras[]"" to name="extras[]"
and i think array starts with 0, and the query would be:
while ($i < $arr_num){
$q = "INSERT INTO bs_reservations";
$q .= " (dateCreated, name, email, phone, comments,status,eventID, qty,dropoff,deodoriser,carpet,carpetrepair,furniture,tabs,urine)";
$q .= " VALUES (NOW(),'".$name."','".$email."','".$phone."','".$comments."','2','".$eventID."','".$qty."','".$dropoff;
$q .= "','".$idextra[0]."','".$idextra[1]."','".$idextra[2]."','".$idextra[3]."','".$idextra[4]."','".$idextra[5]."')";
$res=mysql_query($q) or die('ERROR INSERTING: '.mysql_error());
$i++;
}