how do I pass js variable value to php - javascript

I am trying to pass a random number from html to php
the random number (generated by js), is displayed on the webform and the user must supply its value on the form. php must GET this value and process accordingly.
In my webpage, i have this js and form action;
<script type="text/javascript">var rnd = Math.floor((Math.random() * 100) + 1);</script>
<form name="contactform" method="post" action="http://example.com/example.php&formvar=rnd">
In my example.php, i have
<?php
$rands = $_GET['formvar'];
echo "rands:" .$rands;
?>
In this example, the value of variable formvar is always 'rnd' instead of the value of rnd
Can you please advise the best way to do this ?

To put data from a JavaScript variable into the document (including into form data), you need to write JavaScript that will do that.
You can't just use the variable name as part of HTML.
If you really want to put it in the URL for the form, you could do something like:
<form id ="contactform" method="post" action="http://example.com/example.php">
</form>
<script>
var rnd = Math.floor((Math.random() * 100) + 1);
var form = document.getElementById('contactForm');
form.action =+ "?formvar=" + rnd;
</script>
But you would probably be better off including it in the post data and using an input.
<script>
var rnd = Math.floor((Math.random() * 100) + 1);
var form = document.getElementById('contactForm');
var input = document.createElement('input');
input.name = "formvar";
input.value = rnd;
input.type = "hidden";
form.appendChild(input);
</script>

Related

inserting random number into hidden field on submit

Trying to insert a random number into a hidden field in a form using javascript. Not passing any value since SQL error of - doesn't have a default value
var randomNum = '';
randomNum += Math.round(Math.random()*5);
var elem = document.getElementById("randSS").value = randomNum;
<input name="randSS" type="text" id="randSS"/>
Didn't have protected fillable added!

Random Order Number Post to Email

Hi I have a standard HTML side.
From the final page before submission of form (page3.php), i have all the details already there in hidden fields, once I click "Submit" and email is sent with the details.
I am trying to add a random number, like an order number.
I am able to do it with:
<script>
now = new Date();
randomNum = '#S';
randomNum += Math.round(Math.random()*9);
randomNum += Math.round(Math.random()*9);
randomNum += now.getTime().toString().slice(-6);
</script>
and in html on the form:
Order Number = <script>document.write(randomNum)</script>
<input type="hidden" name="orderid" onload="this.value=randomNum">
This works, a random number can be generated on that page itself (page3.php), however when I click submit, I cant seem to get it to appear in the email. Submit leads to an email.php that sends the form data to my email address. In that email.php I have it sent to collect "orderid" and post it into the email body as "$orderid"
Any idea what I am doing wrong?
Place the JavaScript code which generates the random number after the definition of the <input> element:
<input type="hidden" name="orderId" id="orderId">
<script>
now = new Date();
randomNum = '#S';
randomNum += Math.round(Math.random()*9);
randomNum += Math.round(Math.random()*9);
randomNum += now.getTime().toString().slice(-6);
var order = document.getElementById("orderId");
order.value = randomNum;
</script>
You may want to place your scripts at the bottom of the page for this and other reasons.

call php function in jQuery

The user needs to enter the 4 input fields in order to get the result which is expense. The result will be using FV formula thus I searched online and found out the how FV formula can be used in PHP. Now i want to call the function of the FV formula using the jQuery as i want when the user entered all fields the results will auto come out in the id rExpenses but it doesn't work. It displays a blank page when I go the localhost. Can anyone help? Thank you!
Edit: I deleted the php part and change the code to:
<!doctype html>
<html>
<script>
$(document).ready(function() {
$('input').keyup(function(){
var $rincome = parseInt($('#textfield1').val());
var $rate = parseInt($('#textfield2').val());
var $age = parseInt($('#textfield3').val());
var $rage = parseInt($('#textfield4').val());
var rExpenses = FV($rate/100,$rage - $age ,0,$rincome,0);
$('#rExpenses').html((rExpenses).toFixed(2));
});
});
</script>
<b>Monthly retirement income (SGD):</b>
<input type="number" id="textfield1" value="<?php echo $_POST['rincome'];?>" name="rincome" min = "0" />
</p>
<p>
<b>Inflation rate (%):
<input type="number" id="textfield2" value="<?php echo $_POST['rate'];?>" name="rate" min = "0" step = "0.1"/>
</p>
<p>
<b>Current age:
<input type="number" id="textfield3" value="<?php echo $_POST['age'];?>" name="age" min = "0" max = "70"/>
</p>
<p>
<b>Retirement age:
<input type="number" id="textfield4" value="<?php echo $_POST['rage'];?>" name="rage" min = "0"/>
</p>
<p>
<b>The monthly expenses when you retire(inflation adjusted):<span id = "rExpenses">$0.00</span>
</p>
<script>
function FV(rate, nper, pmt, pv, type) {
var pow = Math.pow(1 + rate, nper),
fv;
if (rate) {
fv = (pmt*(1+rate*type)*(1-pow)/rate)-pv*pow;
} else {
fv = -1 * (pv + pmt * nper);
}
return fv.toFixed(2);
}
</script>
</html>
You can't call a PHP function from within JQuery because JQuery is running in the browser, and PHP is running on the server. You could do it as a remote sort of thing using an AJAX call, but that would be silly. Why not just translate the PHP function into Javascript, and have it on the page?
Looking at the page, I can see what you've done, and it looks like you're wanting to have the server do the calculation. If you want to do that, you'll probably have to create a form and post your values to the server, or, as I said above, do something with AJAX.
If it were me, I'd get rid of the PHP stuff, and have something like this instead (and yes, you can use $ signs in variable names in Javascript, but I'd recommend against this if you're going to mix PHP up with it):
$('input').keyup(function(){
var $rincome = parseInt($('#textfield1').val());
var $rate = parseInt($('#textfield2').val());
var $age = parseInt($('#textfield3').val());
var $rage = parseInt($('#textfield4').val());
var rExpenses = fv($rate/100,$rage - $age ,0,$rincome);
$('#rExpenses').html((rExpenses).toFixed(2));
});
then change your <?php and ?> tags at the end of the page into <script> and </script> tags. It won't work exactly, but you should be able to debug it easily enough in your browser tools.
I think you are confusing two concepts here. PHP runs on server, which means when you call that php function, the result is a html file without any of the php code. So you cannot directly call php function in jquery, which runs on the generated HTML file.
I think translating the php function to a javscript function, which can be directly called is the best option you have now.
The translated javascript function is as easy as below:
function fv(r,n,p,pv=0)
{
var sum = pv;
for (var i=0;i<n;i++ )
{
sum += sum*r + p;
}
return sum;
}
Then your jquery script block becomes
$(document).ready(function() {
$('input').keyup(function(){
var rExpenses = fv(("#textfield2").val()/100, ("#textfield4").val() - ("#textfield3").val(), 0, ("#textfield1").val());
$('#rExpenses').html((rExpenses).toFixed(2));
});
});

Transferring HTML element values, to other files

Let's say I have this piece of code from first.html
<input type="text" id="name">
Go to next page
How can I make it that when you go to second.html, javascript alerts the value of [name] from first.html OR the html adds an h1 tag with the value of [name] from first.html
You can use document.getElementById() function to get input and access it's value property to read what was entered there.
The onclick attribute on your anchor element will execute a custom function which will take the href property of the anchor and append the url-encoded value of the input field.
Then it will go to that new URL.
The return false ensures that built-in href event does not execute.
function link(anchor) {
var name = document.getElementById("name").value
var url = anchor.href + "?name=" + encodeURIComponent(name);
window.location.href = url;
}
<input type="text" id="name">
Go to next page
To read the passed in variable on the receiving page, use the technique described in this SO post:
How can I get query string values in JavaScript?
you could use onclick function on anchor tag.
<input type="text" id="name">
<a onclick="goToNextPage()">Go to next page</a>
<script>
function goToNextPage()
{
var value = document.getElementById('name').value;
window.location.href="second.html?name="+value;
}
</script>
Or you could use form.submit() to post the form values to request.
As HTML is only markup language, not programming language. So, you would need either php/ javascript to fetch that value on second page.
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
and then call that function in your second page as.
<script type="text/javascript">
document.write(qs("name"));
</script>

HTML Form Action URL - add JS variable to URL

I have a JS variable which holds the value of a PHP variable.
<script>
var xxxx = "<?= $v2 ?>";
</script>
I also have a form which points to superman.php
<form action="superman.php" method="get" target="_blank">
I need to amend superman.php so that it holds:
values from elements in the form
and the javascript variable too
How do I achieve this?
Thank you.
You can append hidden input:
addDataToForm('xxxx', xxxx);
function addDataToForm(name, value){
var form = document.getElementsByTagName('form')[0];
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = name;
hidden.value = value;
form.appendChild(hidden);
}

Categories