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
Related
I have a signup form that has an input box hidden from view unless a link is clicked. Here's the code:
<a id="showCoupon" href="javascript:void(0);" onclick="toggleCoupon();">
<?php _e('Have a coupon?','mysite'); ?>
</a>
If the coupon GET variable is set, I want the input box to be visible and prefilled with the supplied data. I added PHP to check for the presence of a GET variable like this:
if(isset($_GET['coupon'])) {
$coupon = $_GET['coupon'];
}
?>
In addition, the input box has been modified to use the value of $coupon, if set. Now, I can't figure out how to trigger the JS event toggleCoupon();.
I modifying the PHP function to click the link like this:
if ( isset($_GET['coupon']) ) {
$coupon = $_GET['coupon'];
echo "<script>$('#showCoupon').trigger('click');</script>";
}
?>
So far, it doesn't work. What am I doing wrong?
have you tried:
<script>
$(document).ready(function(){
$('#showCoupon').trigger('click');
});
</script>
When the document loads, jQuery will trigger the click even of the element with the id of showCoupon
Don't use a kludge like that. That's awful.
Instead, on the server side, don't output the piece of code (CSS class, "display: none;", whatnot) that hides the element in the first place, if the URL parameter is provided.
If the element is hidden by JavaScript, pass it a value indicating that the initial state should be visible.
I've the following problem...
My application uses the php, smarty templates and jQuery.
Inside the smarty template there is defined a form with POST method.
The action parameter of the form is defined as follows:
action={if isset($search_place)} {link->somePhpFunction($search_place) {/if}
...because I need to change the action depending on the POSTED parameter.
The input (text) with the "search_place" name is defined inside the form.
The submit button is linked to the jQuery function, as I need to perform some actions on the client side (value check, autocomplete, etc.).
When the button is clicked, I need to
The problem is that when I post the form by the jQuery button, the form will not take the
When the button is clicked then the jQuery handler is called where some checks/corrections are performed and then the page with the form is displayed.
The problem is, that before defining the action parametr from the form the search_place variable in not known and the php function is not called at all.
I've also tried to set a cookie in the button handler and to set the form action to the {$smarty.cookies.search_place} value but the problem changed into another one - the form allway performes action of the previous button click so it is necessary to click the button TWO TIMES to get the correct results.
It is also necessary to mention that there is no way to transfer the needed action parameter to the jQuery event handler as the php function selects the correct one from the large table in database. If this is possible, then it would be easy to change the action parameter from the jQuery function...
The only way I know is to use AJAX to get the right parametr and assign the correct action parametr from the button event handler but it is not the right solution for me as many of my site visitors have not the browser javascipt enabled.
The solution could be also to perform (programmaticaly) one more click on the button from the jQuery event handler but I don't know how to do it...
Any help or idea how to solve this issue will be greatly appreciated...
Thank you in advance. JaM
Try the following:
<form onsubmit="return validationFunction()">
and let this function validate the data and return true if correct and false if not.
now for the js. don't call something like
$("#someForm").submit();
instead use:
if(validationFunction()){
$("#someForm").submit();
}
Update
finally if your validationFunction will do some server-side work
Then instead some variable like
var formSubmitted = false;
then onSubmit return false; and set the formSubmitted to true, and do your ajax call, and when the ajax call is done, check the formSubmitted if it's true then submit the form if not then show some error...
So basically my question is very simple, I have two buttons, I for page forward, one for page backwards, If one of those is pushed, a javascript function is called inside an onClick Event. Javascript then gets the variables of the page and then redirects to the next page, the only problem is, that I need to pass those variables to PHP in order to put them into the Database. So for that I make a load of cookies to pass the variables.
However, I was wondering if something like this would work :
<form>
<a onClick="nexpage();" onSubmit="phpScript.php"> <img src = "previous button.jpg"/> </a>
</form>
The idea behind this is that I want to store the variables in a PHP script, which will put them in a display:none; <div> and then for javascript to get the variables out. This instead of using cookies.
So is it possible to run a PHP script to get the variables and when the script is finished to get them, Javascript kicks in to redirect to the next page...
The reason I don't test this at this moment, is that my code is 100% complete, I don't want any sudden changes that maybe won't work at all. Yes I know back-up this and that, but I thought just asking here, maybe someone will know the answer!
Sincerly,
Harmen Brinkman
You can also use onClick = "this.form.submit(); return false;".
There is no any event like onSubmit for link, instead form do have onSubmit event.
Normal Way as OP asked.
<form action = "phpScript.php" method = "POST">
you can use document.getElementById("my_form").submit();
#Dipesh Parmar – Good point. You could also do:
window.onload=function() {
document.getElementById('my-form').onsubmit=function() {
// do what you want with the form
// AJAX POST CALL TO PHP PAGE
// Should be triggered on form submit
alert('hi');
// You must return false to prevent the default form behavior
return false;
}
});
Inspiration by Capture a form submit in JavaScript
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.
I've got a bit of a weird problem.
I'm creating a location based web app that is using a javascript function to get a user's GPS coordinates. I have a form with a submit button, and when that submit button is clicked, the function is called (onclick='getCoords()"). The javascript then sets that values of two hidden fields (latitude and longitude) to the GPS coords.
My issue is this: PHP is 'beating' the javascript in the sense that the field values aren't being set in time, so that each value becomes a 0. I've done a bunch of testing, and this is definitely the issue. If I do something like set a seperate button to run the javascript function, the run the form everything works fine.
Any ideas on how to solve this problem?
Gists:
https://gist.github.com/2425419
https://gist.github.com/2425394
https://gist.github.com/2425391
Along the lines of what Volkner said, block submit using a submit handler (call preventDefault), then submit at the end of itsWorking. You can either call .submit() to do the submission, or use AJAX.
I think the crux of your problem is that an <input type="image"> will submit a form just as sure as <input type="submit"> will.
However, to fix this as is, add event as a parameter to both the call and declaration of getUserLocation(event).
Then edit your JavaScript as follows:
function getUserLocation(event) {
event.preventDefault(); // prevents form from submitting
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(itsWorking, notWorking);
}
else {
alert("Dang! Your browser doesn't support finding your location, use the zipcode method below.");
}
};
function itsWorking(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
var finalLat = Math.round(lat*1000000)/1000000
var finalLong = Math.round(longi*1000000)/1000000
$("#longi").val(finalLong);
$("#lati").val(finalLat);
document.getElementById('findoneform').submit(); // submits form since we were successful
};
But like I originally stated, it seems if you used an img tag instead of <input type="image">, that would prevent the form from sending in the first place (and maybe you did this on purpose, because you wanted to have two ways to submit the form?).
This issue happens because the page unloads (submits the form) before the geolocator's done doing its thing, but this way, we stop the form from submitting, and itsWorking() only gets called AFTER the geolocator has done its thing, so we don't submit the form until the end of itsWorking() when we've done everything we wanted to do.