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 :)
Related
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.
I am trying to change the 'src' of an image element and also change the properties of input elements to 'readonly' after a form has been validated and submitted. The validation of the form occurs in PHP so I cannot attach an on submit event handler as it will trigger even if the form has not passed validation. Is there any way to do this without a plugin of some kind?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>
</head>
<body>
<script>
$(document).ready(function()
{
$("#button_img").click(function ()
{
alert("button clicked");
$("#course_name").css("background-color", "yellow");
$("#course_name").attr("readonly",true);
$("#button_img").attr('src','../images/edit_course.png');
});
});
</script>
<form id='design_course' action="<?php ($_SERVER['PHP_SELF']); ?>" method="post">
<label id="course_name_label">Course Name:</label>
<input type=text id="course_name" name="course_design_name" value="default">
<button id="create_course" type="submit" ><img id="button_img" src="../images/create_course.png"></button>
</form>
</body>
</html>
Since the validation logic you're using for this is server-side, the page is going to be changing during a reload. So your logic for conditionally setting values in your HTML would be server-side.
You can conditionally output to the page from PHP based on any if statement. You're not showing the validation logic, but let's assume for the sake of example that if validation passes then there is a boolean variable called $passedValidation. Then you can do something like this in your code:
<?php if ($passedValidation) { ?>
<img id="button_img" src="../images/something_else.png">
<?php } else { ?>
<img id="button_img" src="../images/create_course.png">
<?php } ?>
So note that if the form "passed validation" then the image used is something_else.png instead of create_course.png. So when the page reloads after having passed the validation logic, the user will see the other image.
The same can be done for other HTML output. How you organize it is up to you, as it could get ugly to re-use this same if/else structure for a variety of attributes on the page. Perhaps you can just have two complete forms wrapped in a single if/else block or something like that.
Note also that you'll want a default case of false for $passedValidation to handle when the page is first loaded and no form has been submitted at all.
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.
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.
I have a bunch of links with ID's 1 - n, and I want to pass that ID to a hidden input in my form (I have numerous links but want to only have one form rather than generating thousands of extra lines of HTML making a form for each ID).
The link looks like this:
Remove
The form with hidden input looks like this:
<form action="/php/removeSave.php" method="POST" id="removeSave">
<input type="hidden" name="ID" value=""/>
</form>
Any help?
This sets the value of the hidden input with the id ID to the id of the a element before it submits the form.
<a href='#' id='n' onclick='$("#ID").val(this.id);$("#removeSave").submit();'>Remove</a>
<form action="/php/removeSave.php" method="POST" id="removeSave">
<input type="hidden" name="ID" id="ID" value=""/>
</form>
You haven't provided the full context of the "Remove" link, wherein the ID would be noted, so I will presume a format, and you can adapt from there.
<!-- HTML //-->
<!-- Format for Each Element. "123" is the ID here //-->
<div id="element123">
This is Element 123 (ID#123)
Remove
</div>
<!-- The Form at the Bottom of the Page //-->
<form id="removeSave" method="POST" action="/php/removeSave.php">
<input type="hidden" name="ID" value="" />
</form>
The jQuery Segment
<script type="text/javascript">
$(document).ready(function(){
// Clicks of Links starting with "/php/removeSave.php?ID="
$('a[href^="/php/removeSave.php?ID="]').click(function(e){
// Don't let the Link act as a basic link
e.preventDefault();
// Get the Link HREF attribute
href = $(this).attr('href');
// Derive the Form ID and ID Value
bits = href.match(/^\/php\/([^\.]+)\.php\?ID=(\d+)/);
formID = bits[1];
elementID = bits[2];
// Set the Field Values and Submit the Form
$form = $('#'+formID);
$form.find('input[name="ID"]').val(elementID);
$form.submit();
});
});
</script>
Benefits of this method?
Graceful Degradation - so long as your PHP scripts can also handle GET variables, if this page is loaded from a browser which does not have Javascruipt enabled, or is unable to load jQuery, clicking on the "Remove" links will still perform the expected action.
Opportunity for AJAX-ification - instead of all those other actions inside the .click(function(e){ section, you could use jQuery's $.post() function and the query string segment of the link's HREF to pass this request straight to the handler and manipulate the page without having to do a full-page reload.