views:

49

answers:

3

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.

+1  A: 

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>
tdammers
+1  A: 

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.

Knowledge Craving
Thanks, very helpful :) How do I make sure that "anypage.php" and "rightpart.php" are shown at the same time? :) Including them in the same block? Is that even possible? :)
Latze
+1  A: 

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"&gt;
<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 :)

Álvaro G. Vicario
Wow! Thank you, this was really really helpful! Theres just one tiny bit I don't understand (I'm very new at scripting and all): The parameter "e" in the forms onsubmit function - when/where is it passed to the function, if you know what I mean? :) and if you could please explain to me the line var var currentForm = e.target; ? That would be really nice :)
Latze
See my update --
Álvaro G. Vicario
Thanks! e looks good to me :)
Latze