Can i write some code to execute while my check box is checked in my php code..
my declaration of check box is...
<input id="checkbox" name="click" type="checkbox" onclick="check(this)"/>
i thought to perform a function called check() while clicking the check box..
<script type="text/javascript">
function check(cb)
{
if($("input[type=checkbox]:checked"")
{
//my functionality and operations
}
}
But its not working, how can i perform the onclick event in the Checkbox's action..
First of all, there's a mistake. It should be .is(":checked").
function check(cb)
{
if($(cb).is(":checked"))
{
//my functionality and operations
}
}
And the HTML should be:
<input type="checkbox" onclick="check(this);" />
Or, if you wanna invoke a PHP Function after clicking on Checkbox, you need to write an AJAX code. If this is the case, in your if condition, and checked condition, you can call a PHP file, that calls only this function.
function check(cb)
{
if($(cb).is(":checked"))
{
$.getScript("clickCheckbox.php");
}
}
And you can write JavaScript plus PHP in the clickCheckbox.php file, say something like this:
clickCheckbox.php
<?php
header("Content-type: text/javascript");
unlink("delete.png");
echo 'alert("Deleted!");';
?>
Once you click on the checkbox, and if the state is checked, it gives out an AJAX call to this PHP file, where you are deleting a file delete.png and in the echo statement, you are outputting a JavaScript alert, so that you will get an alert message saying Deleted!.
$('#myform :checkbox').click(function() {
var $this = $(this);
// $this will contain a reference to the checkbox
if ($this.is(':checked')) {
// the checkbox was checked
} else {
// the checkbox was unchecked
}
});
Where your form has id myform
use
if ($('#checkbox').is(':checked'))
or inside an event
$('#checkbox').click(function(){
if ($(this).is(':checked')){
//your routine here if checked
}else{
//routine here if not checked
}
});
You can put like this:
Include the column checked in your table with default value NO.
Then after your SELECT statement show the array.
page1.php
<input type=checkbox value="<?php $row['checked']?>" onclick="location.href = 'update.php?id=<?php echo $row['id']; ?>&checked=<?php if ($row['checked'] == 'YES') { ?>NO<?php } else {?>YES<?php } ?>';" <?php if ($row['checked'] == 'YES') { ?> checked <?php } ?>>
update.php
<?php include('server.php'); ?>
<?php
$id = $_GET['id'];
$checked = $_GET['checked'];
if(isset($_GET['id']))
{
$sql = "UPDATE table SET
checked = '$checked'
WHERE `id` = '$id' ";
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error updating record: " . $conn->error;
}
header('location: page1.php');
}
?>
Try this one
<input id="checkbox" name="click" type="checkbox" onclick="check()"/>
//in js
if( $('input[name=checkbox]').is(':checked') ){
// your code
}
Related
I have the following php code:-
<?php
.....
......
if(isset($_POST['disable']))
{
foreach ( $_POST['users'] as $userid ) {
$wpdb->query("UPDATE ".$wpdb->prefix."usercontrol SET disable_status ='disabled'
WHERE ID = ".$wpdb->escape($userid));
}
}
?>
HTMl
-----
<input type="submit" value="<?php esc_attr_e('Disable'); ?>" name="disable"
id="disable" class="button-secondary action" />
This is the page:-
I need to simply refresh /reload the page, if the user didn't check in any of the check box.
now its throwing error. Need to write an else condition for "if(isset($_POST['disable']))"
Please help.
<?php
.....
......
if(isset($_POST['disable']))
{
if(isset($_POST['users'])) {
foreach ( $_POST['users'] as $userid ) {
$wpdb->query("UPDATE ".$wpdb->prefix."usercontrol SET disable_status
='disabled' WHERE ID = ".$wpdb->escape($userid));
}
}
}
?>
Form submit does reload the page, since in your case it's not bound to an AJAX call. Just added an isset that checks for any value for users in $_POST. Optionally, you can even add an else to display an informative message instead of a plain reload.
I need a simple php function to mimic an Ajax form submission - basically in the form there is a radio button "ajax" and it is either set to yes or no. I just need to mimic successful/failing ajax calls...
HTML
<label for="">Ajax Success*<input type="radio" name="ajax" id="yes" value="yes" checked>Yes<input type="radio" name="ajax" id="no" value="no">No</label>
PHP
<?php
$ajax = $_POST["ajax"];
if(isset($_POST['ajax'] == "yes")) {
echo "success";
} else {
echo "failure";
}
?>
if I remove the isset, I get an 'undefined index' error, if I put it in I get a syntax error but it looks correct to me...
I just need to send back an echo depending on what option is selected for the input 'ajax'
thx
isset($_POST['ajax'] == "yes") doesn't make sense. You want to check if it's set, and then check if its value is equal to "yes":
if(isset($_POST['ajax']) && $_POST['ajax'] == "yes") {
echo "success";
} else {
echo "failure";
}
As your code does, I'll say you use your defined variable like in this example:
<?php
$ajax = $_POST["ajax"];
if($ajax == "yes") {
echo "success";
} else {
echo "failure";
}
?>
Because if the variable has the value "yes" it'll be ok and undefined or other value will end in "failure".
I have a script wher users can find exercise from a database, I have checkboxes for the user to find specific exercises the script works fine when a least 1 checkbox is selected from each checkbox group however I would like it that if no checkboxes was selected then it would the results of all checkboxes.
my checkbox form looks like this
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
ect...
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
ect....
<input type="submit" name="sub" value="Generate Query" />
</form>
and here is my script
<?php
if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
//get the function
include ($_SERVER['DOCUMENT_ROOT'] .'/scripts/functions.php');
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 14;
$startpoint = ($page * $limit) - $limit;
// Runs mysql_real_escape_string() on every value encountered.
$clean_muscle = array_map('mysql_real_escape_string', $_REQUEST['muscle']);
$clean_equipment = array_map('mysql_real_escape_string', $_REQUEST['equipment']);
// Convert the array into a string.
$muscle = implode("','", $clean_muscle);
$equipment = implode("','", $clean_equipment);
$options = array();
if(array($muscle))
{
$options[] = "muscle IN ('$muscle')";
}
if(array($equipment))
{
$options[] = "equipment IN ('$equipment')";
}
$fullsearch = implode(' AND ', $options);
$statement = "mytable";
if ($fullsearch <> '') {
$statement .= " WHERE " . $fullsearch;
}
if(!$query=mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint} , {$limit}"))
{
echo "Cannot parse query";
}
elseif(mysql_num_rows($query) == 0) {
echo "No records found";
}
else {
echo "";
while($row = mysql_fetch_assoc($query)) {
echo "".$row['name'] ."</br>
".$row['description'] ."";
}
}
echo "<div class=\"new-pagination\">";
echo pagination($statement,$limit,$page);
echo "</div>";
}
}
Im new with php so my code may not be the best. If anyone can help me or point me in the right direction I would be very greatful.
OK - I think I have figured it all out. You were right - the main problem was in your isset and isempty calls. I created some variations on your file, and this shows what is going on. Note - since I don't have some of your "other" functions, I am only showing what is going wrong in the outer parts of your function.
Part 1: validating function
In the following code, I have added two JavaScript functions to the input form; these were loosely based on scripts you can find when you google "JavaScript validation checkbox". The oneBoxSet(groupName) function will look through all document elements; find the ones of type checkBox, see if one of them is checked, and if so, confirms that it belongs to groupName. For now, it returns "true" or "false". The calling function, validateMe(formName), runs your validation. It is called by adding
onclick="validateMe('criteria'); return false;"
to the code of the submit button. This basically says "call this function with this parameter to validate the form". In this case the function "fixes" the data and submits; but you could imagine that it returns "false", in which case the submit action will be canceled.
In the validateMe function we check whether at least one box is checked in each group; if it is not, then a hidden box in the "all[]" group is set accordingly.
I changed the code a little bit - it calls a different script (muscle.php) instead of the <?php echo $_SERVER['PHP_SELF']; ?> you had... obviously the principle is the same.
After this initial code we will look at some stuff I added in muscle.php to confirm what your original problem was.
<html>
<head>
<script type="text/javascript">
// go through all checkboxes; see if at least one with name 'groupName' is set
// if so, return true; otherwise return false
function oneBoxSet(groupName)
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked) {
if (c[i].name == groupName) {
return true; // at least one box in this group is checked
}
}
}
}
return false; // never found a good checkbox
}
function setAllBoxes(groupName, TF)
{
// set the 'checked' property of all inputs in this group to 'TF' (true or false)
var c=document.getElementsByTagName('input');
// alert("setting all boxes for " + groupName + " to " + TF);
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].name == groupName) {
c[i].checked = TF;
}
}
}
return 0;
}
// this function is run when submit is pressed:
function validateMe(formName) {
if (oneBoxSet('muscle[]')) {
document.getElementById("allMuscles").value = "selectedMuscles";
//alert("muscle OK!");
}
else {
document.getElementById("allMuscles").value = "allMuscles";
// and/or insert code that sets all boxes in this group:
setAllBoxes('muscle[]', true);
alert("No muscle group was selected - has been set to ALL");
}
if (oneBoxSet('equipment[]')) {
document.getElementById("allEquipment").value = "selectedEquipment";
//alert("equipment OK!");
}
else {
document.getElementById("allEquipment").value = "allEquipment";
// instead, you could insert code here that sets all boxes in this category to true
setAllBoxes('equipment[]', true);
alert("No equipment was selected - has been set to ALL");
}
// submit the form - function never returns
document.forms[formName].submit();
}
</script>
</head>
<body>
<form action="muscle.php" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
<input type="hidden" name="all[]" id="allMuscles" value="selectedMuscles" />
etc...<br>
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
<input type="hidden" name="all[]" id="allEquipment" value="selectedEquipment" />
<br>
<input type="submit" name="sub" value="Generate Query" onclick="validateMe('criteria'); return false;" />
</form>
</body>
</html>
Part 2: what's wrong with the PHP?
Now here is a new start to the php script. It checks the conditions that you were testing at the start of your original script, and demonstrates that you never get past the initial if statements if a check box wasn't set in one of the groups. I suggest that you leave these tests out altogether, and instead get inspiration from the code I wrote to fix any issues. For example, you can test whether equipmentAll or muscleAll were set, and create the appropriate query string accordingly.
<?php
echo 'file was called successfully<br><br>';
if(isset($_POST['muscle'])) {
echo "_POST[muscle] is set<br>";
print_r($_POST[muscle]);
echo "<br>";
if (!empty($_POST['muscle'])) {
echo "_POST[muscle] is not empty!<br>";
}
else {
echo "_POST[muscle] is empty!<br>";
}
}
else {
echo "_POST[muscle] is not set: it is empty!<br>";
}
if(isset($_POST['equipment'])) {
echo "_POST[equipment] is set<br>";
print_r($_POST['equipment']);
echo "<br>";
if (!empty($_POST['equipment'])) {
echo "_POST[equipment] is not empty!<br>";
}
else {
echo "_POST[equipment] is empty!<br>";
}
}
else {
echo "_POST[equipment] is not set: it is empty!<br>";
}
if(isset($_POST['all'])) {
echo "this is what you have to do:<br>";
print_r($_POST['all']);
echo "<br>";
}
// if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
// if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
If you call this with no check boxes selected, you get two dialogs ('not OK!'), then the following output:
file was called successfully
_POST[muscle] is not set: it is empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => allMuscles [1] => allEquipment )
If you select a couple of boxes in the first group, and none in the second:
file was called successfully
_POST[muscle] is set
Array ( [0] => abdominals [1] => calves )
_POST[muscle] is not empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => selectedMuscles [1] => allEquipment )
I do not claim to write beautiful code; but I hope this is functional, and gets you out of the fix you were in. Good luck!
I have an edit_ticket_check.php page like this:
<form name="frm" action="edit_ticket_asso.php" method="post" onSubmit="return validt(frm)">
<table frame=box align=center bgcolor="9966FF">
<b><h2>Enter Ticket Information</h2></b>
</table>
</form>
Then some boxes like this:
<tr><td><font color="BLACK">Ticket Status:</font></td>
<td>
<?php
echo "<select name=\"ticket_status\">";
echo "<option size =15 selected>Select</option>";
if(mysql_num_rows($result4))
{
while($row = mysql_fetch_assoc($result4))
{
echo "<option>$row[ticket_status]</option>";
}
}
else {
echo "<option>No Status Present</option>";
}
?>
</td>
The input values go to a second edit_ticket.php page where it enters the value in a MySQL database.
if($_POST['submit']=="Insert")
{
$ticket_no=$_POST['ticket_no'];
if ( #$_SESSION[username] == 'admin')
{
$assigned_to=$_POST['emp_name'];
}
else
$assigned_to = #$_SESSION[userid][0];
$reassigned_to_team=$_POST['reassigned_to_team'];
$ticket_status=$_POST['ticket_status'];
$comment=$_POST['comment'];
if($ticket_no!=NULL&&$assigned_to!=NULL&&$comment!=NULL)
{
$query1=mysql_query("select count(ticket_no) as total from ticket where ticket_no='$ticket_no';");
$row = mysql_fetch_array($query1);
if ($row["total"]>"0")
{
$query2="UPDATE ticket SET ticket.assigned_to='$assigned_to', ticket.reassigned_to_team='$reassigned_to_team', ticket.ticket_status='$ticket_status', ticket.comment='$comment' WHERE ticket.ticket_no='$ticket_no'";
$result1=mysql_query("$query2");
}
}
}
Now after this I want that if ticket status = 'pending' then a new pop up window will come up and take a time value and then update the time value of ticket by the newly entered time.
For the pop up window I have this code:
<html>
<body>
<p>Click the button to add resolution time with pending ticket.</p>
<button onclick="myFunction()">Pending</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction()
{
var x;
var name=prompt("Please enter Resolution Time","2099-12-31 23:59:59");
if (name!=null)
{
x="resolution_time " + name ;
document.getElementById("demo").innerHTML=x;
}
}
</script>
Now I can't connect these two pages and I'm also unable to pass the values from the new pop up window to old window.
How can i do this?
Since PHP is a server-side language so it can't be dyanamic like JavaScript which is a client-side language, do you have any better idea to do this other way round?
thank you..
Your landing page (the one that your form processor page, edit_ticket.php should redirect to when it's finished) should accept a parameter in the url. Based on that, you can write javascript in the new page to decide whether or not to open the pending window.
For example: at the end of edit_ticket.php,
header("location: landing.php?pending=1");
and then in pending:
<?php
if (isset($_GET['pending']) && $_GET['pending'] ==1){
?><script type='text/javascript'>
window.open('yourpopup.html');
<?php
}
?>
I have a form with 3 checkboxes, and my idea is run some commands if they are selected and do something else if they are not selected.
for($i=1; $i<=3; $i++)
{
if ($_POST['option'.$i])
{
echo "123";
}
if (!$_POST['option'.$i])
{
echo "456";
}
}
But if they are not selected the commands are not executed.. The if statement is correct?
No, what you should be doing is checking them like this:
if (isset($_POST['option'.$i]))
Otherwise, you are just trying to evaluate the boolean form of whatever is in that $_POST element. Why is this bad? Suppose the value of that field were 0. Even though the checkbox was checked, your code wouldn't run.
Documentation for isset()
Sure, that will work just fine.
If you want to slightly de-uglify your code, you can do it this way:
<input type="checkbox" name="options[option_name]" value="1" />
<input type="checkbox" name="options[second_option_name]" value="1" />
if(isset($_POST['options']) && is_array($_POST['options']) {
foreach($_POST['options'] as $option_name => $ignore_this) {
switch($option_name) {
case 'option_name':
// do something
break;
case 'second_option_name':
// do something else
break;
}
}
}
You can use an if ... else:
if ($_POST['option'.$i])
{
echo "123";
}
else
{
echo "456";
}
to avoid checking the same condition twice.