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".
Related
Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.
my goal: I need to verify that if someone has checked the box that they get financial aid, I need to validated that they check the type they are receiving.
Here is what I have so far in the php validation part.
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (!empty($_POST['action']))):
if (isset($_POST['financial_aid'])) { $financial_aid = $_POST['financial_aid']; }
if ($financial_aid === '') :
$err_financial_aid = '<div class="error">Sorry, this is a required field</div>';
endif; // input field empty
the form code:
<p><strong>Are you receiving Financial Aid? </strong><br />
<select name="Financial_Aid" size="1" tabindex="8">
<option value="blank" selected>Please select one</option>
<option value="Yes">Yes, I Receive Financial Aid</option>
<option value="No">No, I Do Not Receive Financial Aid</option>
</select></p>
<p>Please indicate all forms of Financial Aid that you receive:</p>
<p>
<input type="checkbox" name="financial_type" value="<?php ((isset($financial_type)) && (in_array("hope", $financial_type))) { echo "checked"; } ?> " tabindex="9">HOPE Scholarship/HOPE Grant<br>
<input type="checkbox" name="financial_type" value="<?php ((isset($financial_type)) && (in_array("pell", $financial_type))) { echo "checked"; } ?>" tabindex="10">Pell Grant<br>
<input name="financial_type" type="checkbox" value="Yes" tabindex="11">Student Loan<br>
<input type="checkbox" name="financial_type" value="<?php ((isset($financial_type)) && (in_array("loan", $financial_type))) { echo "checked"; } ?>" tabindex="12">Veterans Benefits<br>
<input type="checkbox" name="financial_type" value="<?php ((isset($financial_type)) && (in_array("tuition_reimbursement", $financial_type))) { echo "checked"; } ?>" tabindex="13">Tuition Reimbursement<br>
<input type="checkbox" name="financial_type" value="<?php ((isset($financial_type)) && (in_array("tuition_waiver", $financial_type))) { echo "checked"; } ?>" tabindex="14">Tuition Waiver<br>
<input type="checkbox" name="financial_type" value="<?php ((isset($financial_type)) && (in_array("other_scholarships", $financial_type))) { echo "checked"; } ?>" tabindex="15"> Other Scholarships </p>
My first thought is that I need another if statement.
if ($financial_aid === 'yes') {
} elseif ($hope) { ((isset($financial_type)) && (in_array("hope", $financial_type)))
return true;
} elseif ($pell) { ((isset($financial_type)) && (in_array("pell", $financial_type)))
return true;
} elseif ($loan) { ((isset($financial_type)) && (in_array("loan", $financial_type)))
return true;
} elseif ($veterns) { ((isset($financial_type)) && (in_array("veterns", $financial_type)))
return true;
}
elseif ($tuition_reimbursement) { ((isset($financial_type)) && (in_array("tuition_reimbursement", $financial_type)))
return true;
}
elseif ($tuition_waiver) { ((isset($financial_type)) && (in_array("tuition_waiver", $financial_type)))
return true;
}
elseif ($other_scholarships) { ((isset($financial_type)) && (in_array("other_scholarships", $financial_type)))
return true;
} else {
!empty $err_finanical_type=please select one
return false;
}
}
I'm missing something. I just don't know what. Can someone help me?
First let me say that your checking input enhances the user experience that many miss.
Your question about PHP validation looks to have 3 areas of response:
1) You show the form code using:
Financial Aid and Yes
BUT your if statement shows
$financial_aid === 'yes'
Camel text needs to be the same in your if code to identify the SAME variable and the === identical as Yes is not identical to yes - things to watch and keep in harmony.
2) The id component of each input form field is missing. You are only using 'name="financial_type"'. Name is for sending the data item via a form submission but also using id="financial_type" more easily works to different ids for each radio button/checkbox with javascript or css. If in doubt just do both name="item1" and id="item2" then the same for the next but changed to item2, etc. Best of both worlds until you have situation selecting between a few checkboxs (ex. box 1 is for red box, 2 for blue and 3 for green for example) that is not part of this questtion.
3) You do not show if you are using a form Submit or if you are using
"button type="button" onclick="dosomething()"
where dosomething() is triggered as a submit.
Validating data at the other end can reveal the word "on" instead of checked or unchecked being passed. I have found this with AJAX XMLHttpRequest transfers more than with POST from form submits. If your question was caused by an "on" confirm/validate instead of the check or uncheck status showing... try the dosomething() script below.
The script also shows the standard type of field... lname existing with and input id as well as localStorage array to be transfered. Sending a localStorage and the form Submit won't both work on their own, leaving the localStorage un sent. XMLHttpRequest needs to be used instead to allow both the form fields and the localStorage to be sent to in this case processing on the server by the code in catchby.php
This example has the client sending with a button...
<button type="button" onclick="dosomething();" class="btn btn-primary btn-lg">Complete </button>
that triggers dosomething() ,in the same page, to use Yes or No based on checked or unchecked status to send from javascript to PHP
<script>
function dosomething() {
// Start XMLHttpRequest
var DaData = new XMLHttpRequest();
// where to pass data to
var url = "catchby.php";
// Data items to pass.. lname is a field in the form
var nm = document.getElementById("lname").value;
/* financial_type is the id of checkbox input converted to Yes or No avoiding the constant "on" being sent */
if($('#financial_type').attr('checked')) {
var cb = "Yes";
} else {
var cb = "No";
}
/* svdStorage is the name of localStorage that is not part of the form that is other saved input user has entered saved on their client side computer that stays for next web visits... in this case an array that includes any outside the form data to send. */
var ct = localStorage.getItem('svdStorage');
// variables to be available in catchby.php via $_REQUEST in code
var vars = "nname="+nm+"&ftype="+cb+"&scdStuff="+ct;
DaData.open("POST", url, true);
DaData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Check onreadystatechange for XMLHttpRequest
DaData.onreadystatechange = function() {
if(DaData.readyState == 4 && DaData.status == 200) {
var return_data = DaData.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// OK Send data items and process data transfer
DaData.send(vars);
document.getElementById("status").innerHTML = "Processing...";
}
</script>
Then to receive data being sent here is catchby.php coding...
<?php
$customerInformation = "";
if(!empty( $_REQUEST["name"]))
{
$customerInformation .= "Name: ";
$customerInformation .= $_REQUEST["name"];
}
// this net line will show the Yes or No reflecting the checked status instead of just the work "on"
$customerInformation .= "<br/>The financial requested was: ".$_REQUEST["ftype"];
// convert localStorage array to data items
$zscdStuff = json_decode($_REQUEST["scdStuff"]);
// determine # of array items
$length = count($zscdStiff);
for ($i = 0; $i < $length; $i++) {
// define items in each line of array
// then
// do what is needed with each line item
}
?>
Note... XMLHttpRequest will work with form items and all other variables you want to transfer, async at the same time, while submit only transfers form items.
Using 1)exactly the same names, 2)use parameter id as well as name parameter in each item of submit line and 3)convert the check / uncheck status to an explicit text item like "Yes" and "No" and your results will be what you expect.
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
}
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.
I have a function that sets and unset's a $_SESSION variable depending on what was submitted from the form in my main page.
function if statement:
$_SESSION['search'] = true;
if($_POST['searchtv']){
$_SESSION['searchtv'] = true;
} else {
unset($_SESSION['searchtv']);
}
if($_POST['searchmovie']){
$_SESSION['searchmovie'] = true;
} else {
unset($_SESSION['searchmovie']);
}
The searchtv and searchmovie $_POST variables are set through the below checkboxes:
<input type="checkbox" name="searchmovie" value="movie" <? echo isset($_SESSION['searchmovie']) ? 'checked' : ''; ?>"/>
However the checked value always seems to be false and displays '' so no "checked" is set to display the tick in the box.
I do know that the $_SESSION variable is being set correctly however because in the same file i have another IF statement (below) that works 100%.
if(isset($_SESSION['searchtv'])){
$database->searchTV($_GET['show'], $session->uid);
}
if(isset($_SESSION['searchmovie'])){
$database->searchMovies($_GET['show'], $session->uid);
}
if(!isset($_SESSION['searchtv']) && !isset($_SESSION['searchmovie'])){
$database->searchTV($_GET['show'], $session->uid);
$database->searchMovies($_GET['show'], $session->uid);
}
If i only tick the searchtv checkbox it only runs the searchTV function and so on.. so i know it is being set and works.. just cannot get the feedback to the checkbox to say yes it was ticked when the search button was selected.
#medoix: Try changing this
<input type="checkbox" name="searchmovie" value="movie" <? echo isset($_SESSION['searchmovie']) ? 'checked' : ''; ?>"/>
to this
<input type="checkbox" name="searchmovie" value="movie" <?php if (isset($_SESSION['searchmovie'])) { echo 'checked="checked" '; } ?>/>
You realize that the portion of the code that checks $_SESSION['searchtv'] && $_SESSION['searchmovie'] near the bottom are both !isset. It'll only run if both aren't checked, rather than if they are.