I have situation where I have an accordian and I am referencing a php file gridlist.php within another php file displayvar.php. In other words the context of displayvar.php are shown in the webpage gridlist.php. Now gridlist.php has a checkbox input:
<input type="checkbox" id="foodlike" value="icecrm">I like ice cream</input>
<input type="checkbox" id="foodlike" value="pizza">I like pizza</input>
<input type="checkbox" id="foodlike" value="soda">I like soda</input>
Now when I check on the checkboxes in the table referenced by gridlist.php displayvar.php should be able to display a list of the items checked. For instance it should display if all three checkboxes are checked:
icecrmpizzasoda
If the last one is checked then only soda should be displayed. Keep in mind because this displayvar.php is displayed within the context of the website gridlist.php I used the following command in gridlist.php:
<?php include 'displayvar.php'; ?>
I tried in the displayvar.php to obtained the variables foodlike (as defined by the variable id in the checkbox gridlist.php) from gridlist.php and then echo them based on this snippet of code:
<?php
$like=$_POST['foodlike'];
echo "$like";
?>
How can I tweak this code to get my desired result?
You can achieve this with :
gridlist.php
<form method="post" action="displayvar.php">
<input type="checkbox" name="icecrm" value="icecrm">I like ice cream</input>
<input type="checkbox" name="pizza" value="pizza">I like pizza</input>
<input type="checkbox" name="soda" value="soda">I like soda</input>
<input type="submit" value="Submit">
</form>
displayvar.php
<?php
$icecrm = isset($_POST['icecrm']) ? $_POST['icecrm'] : null;
$pizza = isset($_POST['pizza']) ? $_POST['pizza'] : null;
$soda = isset($_POST['soda']) ? $_POST['soda'] : null;
echo is_null($soda) ? $icecrm.$pizza : $soda;
?>
As you mentioned you did not want a submit button, you'll probably want some sort of "interactive", instant solution and bypass going to the server, i.e. bypass PHP. Since the include 'foo.php'-statement effectively dumps all contents of foo.php into the current file (you could say it "merges them into one"), all interactions happen on the same page. Thinking about your setup as "file A is communicating with file B via the server" is wrong - there is only one file/page.
So, having said all this, my proposed solution uses Javascript and the seemingly omni-present jQuery library, which you will have to include in your page. The snippet below binds an event-handler to the inputs' change-event, which is triggered when a checkbox or radio are checked or the value of a text-input is changed. Then, we append the checked value to a dummy container for display.
$(function() {
var $likes = $('#likes');
// bind event handler to all input-elements
$('input').on('change', function() {
var $input = $(this),
oldText = $likes.text();
if ($input.is(':checked')) {
$likes.append($input.val());
} else {
$likes.text(oldText.replace($input.val(), ''));
}
});
});
label {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="icecream">
<input type="checkbox" name="icecream" id="icecream" value="icecrm">I like ice cream</label>
<label for="pizza">
<input type="checkbox" name="pizza" id="pizza" value="pizza">I like pizza</label>
<label for="soda">
<input type="checkbox" name="soda" id="soda" value="soda">I like soda</label>
<span id="likes"></span>
Edit: This is how I would lay out the "root" file containing the two gridlist.php and displayvar.php, along with the Javascript required to manipulate the DOM:
<html>
<head>
<title>Test</title>
<style>
label {
display: block;
}
</style>
</head>
<body>
<!-- This will be in a file you called 'gridlist.php' -->
<label for="icecream">
<input type="checkbox" name="icecream" id="icecream" value="icecrm">I like ice cream</label>
<label for="pizza">
<input type="checkbox" name="pizza" id="pizza" value="pizza">I like pizza</label>
<label for="soda">
<input type="checkbox" name="soda" id="soda" value="soda">I like soda</label>
<!-- // -->
<!-- This will be in a file you called 'displayvar.php' -->
<span id="likes"></span>
<!-- // -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $likes = $('#likes');
// bind event handler to all input-elements
$('input').on('change', function() {
var $input = $(this),
oldText = $likes.text();
if ($input.is(':checked')) {
$likes.append($input.val());
} else {
$likes.text(oldText.replace($input.val(), ''));
}
});
});
</script>
</body>
</html>
Edit 2:
You still seem to be having problems, so I shall try to clarify why I think you are not succeeding.
Using only PHP, it is not possible to access the value of a checked checkbox without submitting the form back to the server.
To retrieve the value of a checkbox that has been checked by the user, you essentially have only two possibilities.
Option 1: Submit the form using POST/GET
This entails you having a <form> element enclosing the inputs along with a submit button for submitting the form. This is how (probably) 98% of forms on the Internet work. The data in the form is sent, using either the POST or GET method, to the script you specify in the form-tag. Consider this as an example (text omitted):
<form action="handler.php" method="get">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<button type="submit"></button>
</form>
When the user clicks the submit-button, the form is sent to handler.php via the GET method. There, the form data will be available in the $_GET array. Same applies for POST. Now, an often-used approach is to submit the form to the same script via action="#", meaning you need not have a dedicated handler, but can process data within the same script as your form. Obviously, you will have to distinguish two cases: one initial case where no data is set in $_GET/$_POST, and one submission-case when the data is set.
The same applies to data stored in the $_SESSION, btw: again, you will have to tell a server-side script to put the data you want in the user-session; only then will you be able to retrieve it again.
A similar approach I would call "Option 1 b)" is submission via AJAX. This is basically form submission without leaving/reloading the page. Sending the data is done via Javascript and an "XMLHttpRequest". An XHR lets you send any type of data, not only XML. Again, similar logic applies: you serialize the data in some way, provide an endpoint, usually a script, to talk to, and communicate the data to that script via POST/GET. Then your script can handle the data and return a response, which will be available in the JS that initiated the AJAX-request.
Option 2: By accessing the DOM directly
The DOM is the "tree" that is made up of the HTML-elements of your page. Using Javascript, one can access and modify these elements, remove specific ones or add new ones. This API used to be implemented quite differently across browsers, which is why libraries like jQuery or Prototype were created: they provide a unified API across different user agents.
We can use two features of these libraries:
respond to (user-triggered) events
access elements and data stored therein
This is the approach I used in my answer, which I will not repeat here and you can read above. We respond to the event of the user clicking on a checkbox, and access that very checkbox to retrieve the value-data and process it further.
TL;DR
You have two options: submit the form to a script and process the data there; or, manipulate the DOM to catch user-events and pull out the values.
Credit: this is summing up every answer and comment in this thread, especially those of Obsidian Age and Valentin Papin, who both gave great answers that would lead to a clean and functional result.
Related
I'd like to put a small form on my PHP page with a single input and a submit.
The single input will be for a text date (Apr 4, 2021).
Upon submit, I'd like to just display the timestamp for that input next to the form.
I'm hoping this can be accomplished without having to leave the page as usually I need the timestamp in another form I'm working with at the same time.
I've looked at jquery and ajax, but it's a bit outside my expertise. Can someone point me in the right direction?
What I'm hoping to do:
<form id="show_date" method="post">
Payment Date: <input type="text" name="pay_date">
<input type="submit" value="Calculate">
</form>
<div id="result"></div>
Consider the following jQuery Example.
$(function() {
$("#show_data").submit(function(e) {
e.preventDefault();
$.post("./calcPayDate.php", {
pay_date: $("input[name='pay_date']", this).val()
}, function(results) {
$("#result").html(results);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="show_date" method="post">
Payment Date: <input type="text" name="pay_date">
<input type="submit" value="Calculate">
</form>
<div id="result"></div>
jQuery is a Framework for JavaScript. You need JavaScript to be able to perform something in the "background". That something is referred to AJAX. The idea that your browser can send a bit of data to the server and the server can respond without loading an entire web page.
In HTML the default behavior of the Form will send the data, via GET or POST, to another page (usually a server side script).
With JavaScript, or in this case jQuery, we can collect the Value from the form and send just that to your Script. You will then need to handle the data that is returned by the script.
e.preventDefault is an Event command that prevent s the default event of the Form.
$.post() is a shorthand form of the AJAX POST method in jQuery.
$("input[name='pay_date']", this).val() gets the value from a specific input.
function(results) is a anonymous callback function that takes the data sent back and assigns it to results variable.
$("#result").html(results); puts the data into your container.
That's a super crash course for it.
i am very beginner to php,html and web development.Now iam learning php.
And i have a doubt which is exactly same as how to check if input type button is pressed in php?
but i couldn't find any appropriate answers there.Please see the above link...
Actually form submission is done by using Java script, that's why he have something like this in button's onclick="send(this.form)" ...And this button type is not 'submit'but it is 'button' itself and i tried one of the answer that i found there
Using print_r($_POST) to print all Submitted values..But i couldn't find my button there..
My html code
<Form action="user_register.php" method="post">
<input type="text" id="txtEmail" name="textEmail"/>
<input type="button onclick=runjava() Name="Button"/>
</Form>
My Javascript
function runjava()
{
---
----Codes for validation and some animation
document.forms.item(0).submit();
}
please help me regarding this
Yes, you can use jQuery/javascript to do this.
Generally, you should assign either an ID or a class to your input element to easily identify exactly which control fired the event.
Suppose you have this input button:
<input type="button" id="mybutt" value="Click Me">
To alert when button is clicked:
$(document).ready(function() {
$('#mybutt').click(function() {
alert('it was pressed');
});
});
The $(document).ready(function() { bit makes sure that the page (DOM) has loaded all elements first, before it allows the code to bind events to them, etc. This is important.
NOTE THAT before you use jQuery commands, you must first ensure the jQuery library has been referenced/loaded on your page. Most times we do this in the <head> tags, like so:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
but it can be loaded any time before the jQuery code.
I have a HTML form in list.php that submits the data from text box ("item" in below code) to check.php. This check.php validates the text entered to be not empty or white spaces only. After validation, it redirects to list.php for the entered text to be displayed. list.php is below. I want the "add" button to be enabled only when valid text is entered in the text box. I would like this feature to be done with php and probably not with javascript.
I can use "disabled=\"disabled\" in the form, but this does not work in real-time disabling depending on validation.
<form action="check.php" method="post">
<input name="item" type="text" size="25" autofocus="autofocus" />
<input type="submit" value="Add" id="add" />
</form>
You say:
I would like this feature to be done with php and probably not with javascript.
Unfortunately, if you want "real-time" then you're gonna need JavaScript. You'll need it to make AJAX calls to your PHP code to check for validation.
So either A) you don't validate in "real-time" at all, or B) You use JavaScript in one shape or another.
Let's say you opt for B), to use JavaScript, and presuming ALL you need to do is check for an empty string or whitespace, then you can do all of this client-side in JavaScript and not require a server call at all, also making it truly "real-time".
And so, here is my solution, using JavaScript (jQuery) without relying on server calls. This may not be suitable for your current implementation, but just in case it is, this might be helpful.
JSFiddle:
http://jsfiddle.net/VKfrw/1/
JavaScript:
function hasWhiteSpaceOrEmpty(s)
{
return s == "" || s.indexOf(' ') >= 0;
}
function validateInput()
{
var inputVal = $("#myInput").val();
if(hasWhiteSpaceOrEmpty(inputVal))
{
//This has whitespace or is empty, disable the button
$("#add").attr("disabled", "disabled");
}
else
{
//not empty or whitespace
$("#add").removeAttr("disabled");
}
}
$(document).ready(function() {
$("#myInput").keyup(validateInput);
});
HTML:
<!-- give this guy an ID -->
<input id="myInput" name="item" type="text" size="25" autofocus="autofocus" />
This implementation uses jQuery.
As mentioned, if you want this done in real time some javascript will be needed.
However I think this problem is actually more suited to javascript in general. PHP validation can be useful if you need to cross reference for data with data in your database.
eg. In a sign up form, checking a user is not already registered with the entered email address.
But in your case, depending on what you mean by "valid text" it is probably easier and better to use javascript.
There are some great jQuery plugins which make javascript validation really simple.
http://docs.jquery.com/Plugins/Validation/validate
Lets say that I have an HTML page "myPage.php" with a form that uses the GET method and calls itself:
<form name="myForm" action="myPage.php" method="get">
<input type="text" name="input1" />
<input type="text" name="input2" />
.
.
.
<input type="submit" />
</form>
And also, in this page and outside the form, I have an anchor that also calls the page itself, but with a GET variable "myVar" added (a GET variable that is not one of the form's variables):
Now... I wish that all the variables will be persisted no matter whether the form was submitted or the link was pressed.
e.g., if a user was pressing the link, the URL will get the 'myVar=100' + the form variables (as if the form was also submitted together with pressing the link), and vise versa - if the user submits the form, the URL gets the form's vars as well as the "myVar", if indeed it was in the URL.
Is there a way?
Thank you :)
Hence, the easy way is to set the links with
Something
also, change the action in your form to
<form action"myPage.php?var=100" method="get" name="form_name" id="form_name">
...
and they will send the same form. Anyhow, you'll deal with form inputs one way or another, right?
EDIT: Well, if it depends on the link clicking, then:
1.) Receive the myVar in PHP
$myCurrval = $GET['myVar'];
2.) Assign it to a JS var
<script type="text/javascript">
var JOHNNY = <?php echo $myCurrval; ?>
</script>
2.) Add a hidden input
<input type="hidden" id="myVar" name="myVar" value="" />
2.) And change the link to
Something
3.) Then, create a JS method called, yeah, processForm(), who will decide if sets the myVal or not.
function processForm() {
if (JOHNNY != ''){
document.getElementById('myVar').value=JOHNNY;
}
}
This way, your myVar value will propagate only if it was received before (it means, the first time you send it, it will persist). Somehow, I would use $_SESSION to keep things between requests! In fact, it is safer and lot easier!!! :)
Hope it helps.
How do you use a value "submitted" by a form in javascript?
Facts:
It is a PHP document
I'm using JavaScript because I need some timing factors I don't think I can get from serverside-scripts :)
To simplify; what I want is, that when this form is submitted or a button is clicked:
<form method="POST" action="test.php">
<input type="text" name="foo" size="30">
<input type="submit" value="Click me"> //it doesn't have to be submitted
<input type="button" action="some_action" value="Click me"> //an alternative solution
</form>
the value of the text-input named "foo" is displayed elsewhere.
NOTE The form doesn't have to be submitted, what I realy want is, that when you press a button the value can be used elsewhere
Should I use GET instead? Can I just use the $_POST array? Should I use AJAX (which I am completely useless at)? I don't know what to do in this situation.
Since you mentioned that it does not depend fully upon whether the form is submitted or not, so it's more easier to catch the value w/o POSTing / GETing the form. After you have written your interface logic in the body section, you need to write the following code in the footer page at the end:-
anypage.php:-
<form method="POST" action="test.php">
<input type="text" name="foo" id="foo" size="30" />
<input type="submit" onclick="return writeFoo('foo_placeholder', 'foo');" value="Click me" /> //it doesn't have to be submitted
<input type="button" onclick="return writeFoo('foo_placeholder', 'foo');" action="some_action" value="Click me" /> //an alternative solution
</form>
The above code is your code only with some minor modifications, including calling a JS function "writeFoo()" on the "click" event of either a button / submit. This function takes 2 arguments:-
arg - It mentions the destination placeholder ID of the HTML element, in which the value is to be printed.
source - It mentions the source ID of the HTML element, from which the value is to be grabbed / taken.
rightpart.php:-
<div>
<span id="foo_placeholder"></span>
</div>
The above HTML code can be used for any panel, but must be included when the "anypage.php" page is to be shown to the user. This is because the placeholder element must be present when the "foo" element is being called. Be careful to use the same ID both in the "writeFoo()" function calling time & in this page.
footer.php:-
<script type="text/javascript"><!--
function writeFoo(arg, source) {
if(document.getElementById(arg) != null) {
document.getElementById(arg).innerHTML = document.getElementById(source).value;
}
}
// --></script>
And this page should contain the above JS code containing the definition of the "writeFoo()" function.
EDIT, as for #Latze:-
See you can include that "rightpart.php" page either in the same block of "anypage.php" page or in any block of any other page (like "header.php" / "footer.php" page). But the main logic is that both the source ID (from which the value is taken) & the target / placeholder ID (where the value is to be shown) must be present when you are viewing that particular page (in this case, it means when you are viewing the "anypage.php" page).
Hope it helps.
You can read the value from the $_POST or $_REQUEST array on the server side, and insert it into the output anywhere you like - even inside javascript, if you want to. Example:
<?php
$myValue = $_POST['foo'];
?>
<script type="text/javascript"><!--
function writeMyValue() { document.write('<?php echo $myValue; ?>'); }
// --></script>
PHP runs on the server. JavaScript runs on the browser. These two languages do not talk to each other; they don't even run at the same time, not to mention on the same machine. As soon as the user submits the form, the browser requests test.php from the server and the current page is gone forever, scripts and all.
It's really hard to figure out what you want to do exactly, so I'll provide you with some general hints:
JavaScript can intercept a form submission. You need to attach an onsubmit event handler to the <form> element. The function assigned to the event can do whatever it needs and then return true (and let the submission go on) or return false (and cancel the submission).
JavaScript can read and write almost any page element. You need to use the so called DOM methods.
PHP can generate whatever you need, including HTML input fields.
Example:
<?php
$foo_value = date('Y-m-d H:i:s');
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript"><!--
window.onload = function(){
var documentForms = document.getElementsByTagName("form");
for(var i=0, len=documentForms.length; i<len; i++){
documentForms[i].onsubmit = function(e){
var currentForm = e.target;
var fooValue = currentForm.elements.foo.value;
var p = document.createElement("p");
p.appendChild(document.createTextNode("Aborted submission: " + fooValue));
currentForm.appendChild(p);
return false;
};
}
};
//--></script>
</head>
<body>
<form method="POST" action="test.php">
<input type="text" name="foo" value="<?php echo htmlspecialchars($foo_value) ?>" size="30">
<input type="submit" value="Tryk her">
</form>
</body>
</html>
Update
A little note about this:
documentForms[i].onsubmit = function(e){
};
When you assign an event handler, the spec requires that whenever the function gets called it will receive an event object as its first argument. That object represents the event that triggered the function call and it can be used to obtain additional information, such as the original DOM node that triggered the event. It doesn't matter how you call it inside your function; I use e because I never know how to name stuff :)