This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript post request like a form submit
I have a value calculated in JS that I'd like to pass as part of an input form to a PHP script. How can I get a value the JS value to the PHP as a POST parameter?
Basically, on submit, I need the total var to be passed via post to the next script.
The first idea that comes to mind is create an invisible input form that has the value in it and is inputted with the form, is that possible?
There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.
create this form element inside your form:
<input type="hidden" name="total" value="">
So your form like this:
<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
Click to submit
</form>
Then your javascript something like this:
<script>
function setValue(){
document.sampleForm.total.value = 100;
document.forms["sampleForm"].submit();
}
</script>
Yes you could use an <input type="hidden" /> and set the value of that hidden field in your javascript code so it gets posted with your other form data.
You can do this using Ajax. I have a function that I use for something like this:
function ajax(elementID,filename,str,post)
{
var ajax;
if (window.XMLHttpRequest)
{
ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
}
else if (ActiveXObject("Microsoft.XMLHTTP"))
{
ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
}
else if (ActiveXObject("Msxml2.XMLHTTP"))
{
ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
}
else
{
alert("Error: Your browser does not support AJAX.");
return false;
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4&&ajax.status==200)
{
document.getElementById(elementID).innerHTML=ajax.responseText;
}
}
if (post==false)
{
ajax.open("GET",filename+str,true);
ajax.send(null);
}
else
{
ajax.open("POST",filename,true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(str);
}
return ajax;
}
The first parameter is the element you want to change. The second parameter is the name of the filename you're loading into the element you're changing. The third parameter is the GET or POST data you're using, so for example "total=10000&othernumber=999". The last parameter is true if you want use POST or false if you want to GET.
Your idea of an hidden form element is solid. Something like this
<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>
<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>
Of course, this will change the location to script.php. If you want to do this invisibly to the user, you'll want to use AJAX. Here's a jQuery example (for brevity). No form or hidden inputs required
$.post("script.php", { total: getTotalFromSomewhere });
Related
I'm trying to submit the document (return_url) only after the countdown finishes. In my current code below the document is submitted just after the countdown starts. How can I make the countdown finish before submitting the document_url?
Code:
<body>
<center>
<form name="redirect"><font face="Helvetica"><b>
Thank you! You will be redirected in<input type="text" size="1" style="font-size:25px" name="redirect2">seconds.</b></font>
</form></form>
</center>
<form name="return_url" method="post" action="confirm.php">
<input type="hidden" name="order" value="1" />
<input type="hidden" name="price" value="100" />
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
var targetURL="<?php print_r($_POST['url_retorno']);?>"
var countdownfrom=10
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=1){
currentsecond-=1
document.redirect.redirect2.value=currentsecond
} else {
window.location=targetURL
return
}
setTimeout("countredirect()",1000)
}
countredirect()
document.return_url.submit()
</script>
Big point, you shouldn't automatically submit forms for users, it's kind of a bad UX design. Instead, you could do the wait before submiting thing which disables the button until the timer is up. And for that, you just need to make use of javascript timers.
var timer = window.setInterval(updateClock,1000);
var countdown = 10;
function updateClock() {
countdown--;
if(countdown<=0) {
window.clearInterval(timer);
//ALLOW THE FORM TO SUBMIT
document.getElementById("elementID").disabled = false
} else {
document.getElementById("elementID").value = "PLEASE WAIT "+countdown+" SECONDS";
}
}
I'm also adding in a side point that you should never trust what people put into forms. Lookup XSS or cross site scripting, and SQL injection to find out why. So you need to use validation (even for numbers). If you want on page validation (which still isn't really secure since it can be by-passed) you could add a onSubmit="validate()" attribute to the form tag to call the validate() function when the user does finally submit it. Using this function also gives you the power to take over the form if needed, since you can execute any javascript you want there and simply returning a "false" value will cause the form to NOT submit.
ALWAYS VALIDATE YOUR FORM ENTRIES ON THE SERVER LEVEL (ie. in the confirm.php file)
Try the following:
setTimeout(function() {document.return_url.submit();}, 10000);
That should be all you need.
Or if you want to display the timer, use setInterval();
var seconds_left = 10;
var timer = setInterval(countdown, 1000);
function countdown() {
seconds_left--;
if (seconds_left) {
console.log(seconds_left); //or modify the DOM
} else {
document.return_url.submit();
clearInterval(timer);
}
}
id doesn't want to put the value in to the document.getElementById("UniLoc").value = val; and it doesn't want to submit the form how to fix this ?
This is how I call the function JS nas some value "asd56"
echo "
<script type="text/javascript">
repostD("'.$JS.'");
</script>";
here is my function inside
<script>
function repostD(val)
{
//document.getElementById("UniLoc").value = val;
document.getElementById('UniLoc').innerHTML = val;
//document.UlRL.UniLoc.value = val;
document.forms["UlRL"].submit();
}
</script>
and here is my form in html
<form name="UlRL" id="UlRL" action="in.php" method="post">
<input type="text" id="UniLoc" name="UniLoc" value="<?php echo $UniLoc;?>" />
Use
document.getElementById('UniLoc').value=val;
If there is nothing else wrong with your full form, it should submit. If you haven't closed your form tag, then close it.
</form>
try doint that in php all instead of in function make an if clause down the code that will execute the action of the posting of the form and at the beggining of the php try this
if($JS!="" )
{
$UniLoc=$JS;
$JS="something that will go throught the other if down at the code";
}
else {
$UniLoc=$_POST["UniLoc"];
}
I cant really tell from your question what is wrong, but looking at your code:
document.getElementById('UniLoc').innerHTML=val;
you are trying to set the value of the input with id 'UniLoc', but you are using the wrong syntax. Instead of .innerHTML, use .value
document.getElementById('UniLoc').value=val;
I have a comment system in which i want to add delete option, for this i have implemented a POST form in each comment which posts comment-id to delete.php, it is working in php, but not in jquery.
i.e in order to delete comment a comment id must be posted to delete.php file which handles deletion of comment from database.
i am trying to fetch that comment-id from input value to post with jquery like this but it gives me the first comment-id value not the selected value.
Jquery
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]").val();
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
repeating form is like this
<form name="comments" action="../../delete.php" method="post">
<input name="comment-delete" type="hidden" value="<?php echo $list['comment-id']; ?>" />
<input value="Delete" type="submit" />
</form>
if i use .each() or .map() it gives me all the comment-id values.
Please see and suggest any possible way to do this.
Thanks.
To find the relevant input, that is the one of the form you submit, you could use this :
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
BTW, I'm not totally sure of what you do but you might be missing a .val() to get the value of the input.
You have the same name on each hidden input, naturally you get all those inputs as you have not targeted the correct form when doing:
$("input[name=comment-delete]");
"this" whould point to the form inside your submit function. Try this.
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
As dystroy said, you are probably missing .val().
var commentId = $(this).find("input[name=comment-delete]").val();
try this
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]", this);
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
this refers to the form being submitted (more generally, to the event source).
$(...) accepts a second parameter, which is then used as a context for the selector. $(selector, context) is equivalent to $(context).find(selector)
How can I check a input field exists in the form when I submit it to the server?
For instance, I want to check whether a check box named 'mem_follow' exists or not in the form.
Or do I have to use javascript (jquery)?
I'm guessing you need to check on the server side after the form is submitted. If that's the case, you can check like so...
<?php
if (isset($_POST['mem_follow']))
{
// Work your server side magic here
} else {
// The field was not present, so react accordingly
}
?>
Hope this helps!
It'd HAVE to be Javascript. PHP can't reach out from the server into the browser's guts and check for you. It could only check if the fieldname is present in the submitted data.
In jquery it's trivial:
if ($('input[name="nameoffield"]')) { ... field exists ... }
Of course, this raises the question... why do you need to know if a field exists or not? Presumably you're the one who's built the form. You should know already if the field exists or not.
In the following script the form will not submit unless the checkbox is ticked. And If you do try, the hidden div with an error message is shown, to let you know why.
<form action="test.php" method="post" id="myform">
<input type="checkbox" name="checkbox" id="checkbox" value="YES" />
<input type="submit" name="submit" value="submit" />
</form>
<div id="error_message_div" style="display:none">You must tick the checkbox</div>
<script>
$('#myform').submit(function() {
if($('#checkbox').attr('checked')) {
return true;
} else {
$("#error_message_div").show();
return false;
}
});
</script>
Cheers
Matt
you can do this in two way:
By Server Side: In php
<?php
if (isset($_POST['mem_follow'])
{
// Work your server side magic here
} else {
// The field was not present, so react accordingly
}
?>
By Client side: In Jquery
$('#submit_button').click(function() {
if ($('input[name="box_name"]')) {
if($('input[name="box_name"]').attr('checked')) {
return true;
} else {
return false;
}
}
});
You can use jQuery and do something like this:
$('#myForm').submit(function (e) {
if($(this).children(':checkbox[name=mem_follow]').length > 0)
//exists
else
//doesn't exist
});
Or use php and check if there is any variable named 'mem_follow': (this is for POST, although it doesn't matter if it's GET or POST)
if(isset($_POST['mem_follow']))
//exists
else
//doesn't exist
You can try this code in the form submit event handler
if($("input[name=mem_follow]").length > 0){
//It exists
}
The other answers here are correct: you'd have to do that on the client side. In the case of a checkbox input field, if the box is not checked there is no guarantee the browser will include a POST parameter for that field.
For example, if you submit this form without checking the checkbox:
<form action="test.php" method="post">
<input type="checkbox" name="checkbox" value="YES" />
<input type="submit" name="submit" value="submit" />
</form>
only the submit=submit parameter will be submitted.
So, no, you cannot guarantee that a given checkbox exists in a form on the server side.
well for all elements try this
number = document.form_name.elements.length;
else for a specific name of input use this
number = document.form_name.getElementsBYName('Name of Input').length;
Thats it
enjoy
I suggest you to use Jquery
$.fn.Exists = function() {
return $(this).length>0;
}
if ($("here are your selector to check").Exists()) {
...
}
Simple and useful!
And you can use this Exists method everywhere))))
You can use javascript (or jQuery) to do that :
<script>
$('#myform').submit(function() {
if($('#yourFieldId').val()=='') {
alert('the field ' + $('#yourformField').name() + ' is empty !');
return false;
} else {
return true;
}
});
</script>
you can do this for all your fields one by one, or by putting all conditions in the if statement.
I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>