POST value not show in javascripts - php

from my this code
<script type="text/javascript">
function getValue()
{
console.log("<?php echo $_POST['input_value'] ; ?>") ;
return false ;
}
</script>
<form id="request_form" action="" name="request_form" method="POST" >
<input id="input_value" type="text" size="45" name="input_value"></br>
<button class="button" id="btForm" onclick="return getValue()" >submit</button>
</form>
I expect it will print some value that I put but it show nothing.
What am I wrong?

Your form isn't actually submitting to a php page. It's just calling getValue, which won't have anything in it yet.
There are two halves to what you are trying to do, and your mistake is that you have mixed them together. The first is the server side, with the PHP. When you submit a form, you should use:
<input type=submit value="Submit" />
This refreshes the page (because the form action is blank), which, using PHP, can read your POST value and print it back out along with the rest of the page. Once the page is finished loading, PHP is no longer involved and cannot affect the behavior.
As you have it right now, when you load your page it looks like this:
<script type="text/javascript">
function getValue()
{
console.log("") ;
return false ;
}
</script>
Since the POST value wasn't there the first time the page loaded, the javascript sent to the browser looks like that - there is no value to print. Clicking the button will execute getValue() as it appears here.

PHP is server side, and is done before the page is loaded in the browser. When first loaded there is no $_POST at the time, so the log is empty.
When submitting the form, you are calling the console.log function which has no text in it, and then returning FALSE, so the form never actually gets submitted.
You need to either set the action attribute in the form tag to point to a PHP page to process the $_POST data, or you need to use AJAX to post the form.

function getValue() {
console.log(document.request_form.input_value.value) ;
return false ;
}
could have a sense, at the moment whe you execute getValue () in JS (client-side) - PHP (server-side) is not involved so no way to echo $_POST....

You can't write out actual server-side code from javascript, and expect it to execute client-side.

Related

PHP $_POST is empty after using jquery val() on input

I want to check value of input for year of birth. I have figured out that if I use jquery function val() to get value of this input, so the php post of this input will be empty. It works fine without using val(). Here you can see the important part part of code. It is not so essential ability of form, but it would be useful to check if the isn't written anything inappropriate or any mistype.
Thank you for help.
<?php
if (!empty($_POST['rn']) && isset($_POST['rn'])){
// proceed
} else {
echo "You haven't filled all inputs";
}
?>
<script>
$("#kontrolaButton").click(function(){
var rok = parseInt($("#rok_nar").val(),10);
if (rok > 1900 && rok < 2016) {
$("#odeslatButton").trigger('click');
};
});
</script>
<form accept-charset="utf-8" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="send_form">
<input class="bold" id="rok_nar" type="text" name="rn" placeholder="Rok narození"/>
<input type="button" value="Odeslat" name="kontrola" id="kontrolaButton" />
<input type="submit" value="Odeslat" name="odeslat" id="odeslatButton" style="visibility: hidden;" />
</form>
Update:
I have probably found the problem. I didn't write it here, because I didn't consider it as an issue. My script looks like:
$("#kontrolaButton").click(function(){
var rok = parseInt($("#rok_nar").val(),10);
alert(rok);
if (rok > 1900 && rok < 2016) {
$("#odeslatButton").trigger('click');
};
});
After erasing the alert, the code works :/ Interesting...
It looks like your trying to access an input in the dom before it is loaded. I don't see a document ready. You need to either stick your script inside a document ready so it is delayed until the dom is completely parsed, or move your logic at the bottom of your page so the elements exist by the time you try to look them up.
You should move the script right to the end of the HTML body so that it executes when the kontrolaButton element is in the DOM.
Note that the mouse down/up or key press/release you issue to close the alert(rok); may interfere with the submission of the form. For instance, I could reproduce a problem like this: I pressed the ESC key to close the alert, and although the form submitted its data, the next page did not render; it was just a blank page. This may be very browser dependent, but on my set-up the ESC key apparently interrupts the rendering of a page.
There may be other such side effects, certainly also if you have other Javascript code on the page that responds to these key or mouse events.

php : cannot see the hidden value submitted by Javascript

I'm pretty sure I'm missing something simple here, but it's driving me nuts !
This isn't the first form I'm using in PHP, but the first time submitting a hidden value.
When a menu item is clicked, I want to submit the page to itself - setting a simple parameter, so the php code does the processing.
The page gets submitted fine, but the hidden variable I set isn't available through _GET, _POST or _REQUEST. It should be _GET since that is what I've set as the method.
Here is the code if anyone can spot where I'm going wrong..
paramCustom is the one that I'm trying to set and work on.
The menu is a series of DIVs & anchors :
Option Xyz
The activateMenu javascript function is :
function activateMenu(optionTaken)
{
// Set the hidden variable
document.getElementById('paramCustom').value = optionTaken;
// Display it to confirm it is set correctly
var tt = document.getElementById('paramCustom').value;
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
The form is coded this way :
<form method="get" action="showProducts.php" id="linkSubmit">
<input type="hidden" id="paramCustom" name="paramCustom" />
<input type="submit" tabindex="-1" style="display:none;" />
</form>
In the php of the same page I'm trying to spit them out but all of them show blank !!
echo "paramCustom get is : ".$_GET['paramCustom']."<br/>"; // This should work
echo "paramCustom request is : ".$_REQUEST['paramCustom']."<br/>";
echo "paramCustom post is : ".$_POST['paramCustom']."<br/>";
OK, problem is that you are not actually stopping the event from firing. So clicking on the link, the function gets called, form submitted but you are not actually stopping the event in the onclick. So form submits but is immediately redirected to the href of the link cancelling the form submit. When the href is blank, it defaults back to the page you are currently on.
The way you are adding the onclick to the link (using an inline attribute) is like wrapping the event in a closure. So when onclick fires, what is really fired is more like function(){ activateMenu('option-xyz'); }. Your call to activateMenu is returning false, but the closure around it is not. You can just add return in front of activateMenu to have the event itself return false and cancel. Change the link like so:
Option Xyz
And then the actual event itself will return false, not just the function.
Here is a simple example to illustrate what is happening.
Doing a little change to the HTML you can set the inline event via Javascript, which is a way better:
<a id="xyz" href="#">Option Xyz</a>
And this is the Javascript edited for your purpose:
function activateMenu(optionTaken)
{
var paramCustom = document.getElementById('paramCustom');
// Set the hidden variable
paramCustom.value = optionTaken;
// Display it to confirm it is set correctly
var tt = paramCustom.value;
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
window.onload = (function() {
document.getElementById('xyz').onclick = function() {
activateMenu('option-xyz');
};
});
In PHP, as you know, $_GET gets the parameters of query string, $_POST of the POST data and $_REQUEST is a concat of the two arrays. In this case your method is GET so the value can be retrieved via _GET and _REQUEST, _POST is not going to work. Your code didn't worked to me probably because you had your function defined before DOM was loaded, so the event, when fired, probably throwed an exception.
This doesn't work because you haven't assigned a value. PHP won't recognize a field with a null value.
<input type="hidden" id="paramCustom" name="paramCustom" value="somevaluehere" />
[edit]
After testing this myself, it's because the onclick event is not behaving the way you anticipate. The easiest way to fix this is to use a HREF for you link. It's actually bad practice to rely solely on the onclick event anyway.
Option Xyz
This works perfectly.
The proper way to write an onclick looks like this:
Option Xyz
This works as well.
I've been using JQuery lately and it might be worth a shot.
Download the latest JQuery script and just link it to your page.
function activateMenu(optionTaken)
{
// Set the hidden variable
$("#paramCustom").val() = optionTaken;
// Display it to confirm it is set correctly
var tt = $("#paramCustom").val();
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
This isn't that much different than what you had but maybe JQuery will do a better job of assigning the value to your hidden field...
Cheers,
K

Outputting variable value into innerHTML with JQuery and then storing it in PHP variable

Essentially, I'm attempting to capture the value of a HTML drop down menu and call a php function (i.e., print_wp_cart_button_for_product) with the user selected row. I have created a JQuery function which is called onchange, but have encountered several problems. By using alerts, I'm sure that the function is called and that the value is stored in currentrow. Additionally, by using the firefox web console, I know that order.php is called with the appropriate parameters. Originally I was using ajax success method, but the function was not being called, so I switched it to the complete method, which at least solved the fist problem. The second issue I'm dealing with involves storing the variable currentrow in the innerHTML of test. When I changed $('#test').html(currentrow) to $('#test').html("Complete") the string was outputted to the screen, as I would expect, but I've been unable to do so dynamically with the value of the currentrow. The last problem I've found involves saving the value of the test div tag into a php variable. I've attempted to use $_GET to capture the value and subsequently call my php function, but have had no luck.
<div id="test">
</div>
<script type = "text/javascript">
function productchange()
{
var currentrow = $('#productcategory1').val();
//alert(currentrow);
$.ajax({
type: "GET",
url: "http://www.example.com/wp-content/themes/themeX/order.php",
data: {'rownum': currentrow},
complete: function(currentrow){
//alert('COMPLETE');
$('#test').html(currentrow);
//$('#test').html("Complete");
}});
return false;
}
</script>
<?php $rownum = $_GET['test']; ?>
<?php echo print_wp_cart_button_for_product($products[$rownum]["Product"], $products[$rownum]["Price"]); ?>
Order.php
<?php
$rownum= $_GET['rownum'];
echo "Row number = $rownum";
?>
It seems like your <div id="test"></div> should really be <input type="hidden" id="test" name="test"/> within a <form>
Using a form element of some kind is the only way you can natively pass a value back to the server on submit.
In any case, the inline PHP code after your HTML will only work after submit of a form.
Here is a snippet of code that will submit a hidden form field to the PHP page allowing you to store the value in a PHP variable. First, do something like this on the main page which has your javascript.
<form method="post" action="storevar.php">
<input type="hidden" name="jsvar" id="jsvar" value="" />
</form>
Then, after you have calculated the value that variable should be in javascript, update the value of this hidden form field with Javascript/JQuery, like this:
function productchange() {
var currentrow = $('#productcategory1').val();
$("#jsvar").val(currentrow);
$.post('storevar.php', {jsvar: currentrow}, function(data) {
// do any additional coding with the result if need be
}
});
return false;
}
Then you could do something like this in storevar.php. Notice I'm storing it in a session so that it can be retrieved in other pages as well if you need to.
session_start();
$currentrow = $_POST['jsvar'];
$_SESSION['currentrow'] = $currentrow;
I hope that helps you. If you need any additional help, or if I've misunderstood something, please let me know and I'd be happy to help.

Creating function & then calling it when needed

I dont know much about PHP functions.I want to print the name inside the function when it is called on clicking the button.I have tried different ways and even searched for it in google.Need help...
<?PHP
function writeName()
{
echo "Kai Jim Refsnes";
}
Echo "<form>
<input type='button' onClick='writeName();' style='position:fixed;bottom:0px;left:0px;width:100%;'>
</form>";
?>
You can't call a PHP function from JavaScript.
PHP is interpreted on the server side and JavaScript on the client side.
You could use an AJAX request or you could write a JavaScript function at runtime with the PHP
Something like:
echo <<<END
<form>
<input type='button' onClick='function writeName() { document.write("{$php_var_name}") }' style='position:fixed;bottom:0px;left:0px;width:100%;'>
</form>
END
I can provide you with three alternatives:
1. Using pure PHP.PHP is server-side Changes in pure PHP takes place in the following way
Data is sent to the server
Data is processed at the server
After processing data is responded from the server to the user
During the above processes page reloads and when complete data is received at the client reload stops.
So using pure PHP i can figure out only one way to call function on button click.I can be done as follows:
<?PHP
function writeName()
{
echo "Kai Jim Refsnes";
}
if(isset($_GET['submit']))
{
writeName();
}
?>
<form action="#">
<input type="submit" name="submit" value="submit" style="position:fixed;bottom:0px;left:0px;width:100%;" />
</form>
2. Using Javascript.Javascript is client-side.It doesnt reload the page.
<script>
function writeName()
{
document.write="Kai Jim Refsnes";
}
</script>
<button onclick="writeName();">submit</button>
3. Using AJAX.With AJAX you can combine both PHP and Javascript.For this simply print a message AJAX will be too much but for larger/complex data transfers between server and client without reloading AJAX is much helpful.
AJAX refrences: http://api.jquery.com/jQuery.ajax/ ; http://www.w3schools.com/ajax/
PHP is run on the server side, so you should use AJAX, which allows you to run PHP after a page has already loaded.
AJAX is asynchronous javascript - you basically use Javascript to query a PHP page on your server, and you receive a response that you then can print to your page.

Showing an alert() dialog box if a form does not have valid values

I have a simple form which accepts a Title and a Contents variable from a textbox and a textarea. The form will send its data to a file called add-post.php. However, I am looking for a way to alert the user that either the textbox or the textarea has invalid data (is empty) in case they click the submission button.
I was thinking that an alert() popup box would be the best idea because it doesn't redirect to any other page and the user never loses their data (imagine they entered a whole lot of text but forgot a title. Sending the data to add-post.php and performing the check there will result in loss of data for the user).
However, I'm not sure how to actually implement the alert() popup. How would I make it so that the check is done AFTER they have clicked the submit button but BEFORE the data is sent off to the next file. Any advice is appreciated.
On your form add something like this
<form name="frm1" onsubmit="InputChecker()">
Then in javascript
<script type="text/javascript">
function InputChecker()
{
if(document.getElementById({formElement}) != '') { // not empty
alert("This element needs data"); // Pop an alert
return false; // Prevent form from submitting
}
}
</script>
Also as others have said jQuery makes this a little bit easier. I highly recommend the jQuery Validate Plugin
Some people do find the alert box "annoying", so it may be better to append a message into the DOM to let the user know what needs to be fixed. This is useful if there are numerous errors as the errors will be more persistent allowing the user to see all the things they need to be fixed. Again, the jQuery Validate plugin has this functionality built in.
Attach an onsubmit event to the form, and return false; to stop the submission if checks fail.
Form validation with Javascript. Or easier with jQuery.
Basically, validate the form when the submit button is clicked (with an onsubmit handler), and then use an alert() box if needed. By the way, people usually hate alert boxes.
You have a number of options when it comes to client side validation. This is just one.
<form id="tehForm" method="post">
<input type="text" id="data2check" >
<input type="button" id="btnSubmit" />
</form>
<script type="text/javascript">
function submit_form(){
if(document.getElementById("data2check").value!="correct value"){
alert("this is wrong");
}else{
document.getElementById("tehForm").submit();
}
}
</script>
For a more indepth example check out this link

Categories