Passing PHP variable [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a PHP array:
foreach($xpath->query('//a') as $element) {
$linklabel[] = $element->textContent;
$link[] = $element->getAttribute("href");
$i=$i+1;
}
I also have an HTML form:
<form name="keypad" id="form" onSubmit="return pass(this)">
<input type="text" size="100%" length="25" value="" name="lcd">
<input type="button" value=" 1 " name="one" onClick="this.form.lcd.value+=this.value">
<input type="button" value=" 2 " name="two" onClick="this.form.lcd.value+=this.value">
<input type="button" value=" 0 " name="zero" onClick="this.form.lcd.value+=this.value">
<input type="submit" name="Submit" id="Submit" value="Go" >
</form>
How can I write the onSubmit function pass() that takes the values from the keypad and sends the corresponding $link[] value to browse.php. For example, if $link[20]='google.com'; , I want to pass $link[20] to browse.php if user enters 20 in the keypad and presses Go.

You'll need to output the PHP array in a way the Javascript can interpret, like as a Javascript array:
<?php
echo "<script type=\"text/javascript\">\n";
echo "var links = [";
foreach($links as $link)
echo "'$link', ";
echo "];\n";
echo "</script>\n";
?>
You also need an element in the form the function can set:
<input type="hidden" name="url">
Then your Javascript function can index into the array and modify the form element:
function pass() {
id = parseInt(document.getElementsByTagName('form')[0].lcd.value, 10);
document.getElementsByTagName('form')[0].url.value = links[id];
}
Your button values have spaces around them for some reason; they should just be the number, or lcd.value will end up with spaces throughout it. If you want the buttons to have padding use CSS.
Finally, you need to post the form if you're going to check $_POST on the other end, so change the tag to:
<form name="keypad" id="form" method="post" onSubmit="return pass()">
You can also just use $_GET on the target page

Related

Javascript button click change / create PHP variable on same page

I have searched stackoverflow for the past hour and have found similar questions but attempting the solution has given me only errors - it may be as I am trying to load it on the same page.
I have tried saving the value to a cookie in JS then loading it in php, also attempted through ajax, etc.
From what I've read it can't just be done within as PHP is server side and Javascript is browser side which I get.
I currently have a .html page with a form that sends values through POST:
form.html
<form id="calc" form name="calculator" method="post" action="/calculate.php">
The solution is not with the form, I can't have hidden fields as I need to user input. I could have a radio box in the form yes and then get the value that way, but that's not my question. My question is how I can get the user's input and turn it into php on the page the form redirects to calculate.php:
calculate.php
<?php
if(isset($_POST['submit'])){
$x= $_POST['value'];
echo "your something:";
echo $x;
?>
Click button below for option one to do this, or click two for that, or three for something else...
<button id="one"> one </button>
<script>
$(document).ready(
function() {
$("#one").click(function() {
make php value 1
});
</script>
use php value from click
So the user will already have clicked submit. Then be redirected onto the .php page with their inputs, they can then choose button 1, 2 or 3 for example through javascript on calculate.php NOT the form.
My problem is I need to know on the same page - calculate.php, which button has been clicked in php. So that I can use their input and do different things with it depending on which button.
Is it possible to get a value to be set or create one from a button click on calculate.php itself with the javascript button producing a php value on the same page? Does it need to be loaded from an external.php page through ajax? Is there any other way?
PHP Option:
<?php
if(isset($_POST['submit'])){
$x= (isset($_POST['one'])) ? $_POST['one'] : '';
$y = (isset($_POST['two'])) ? $_POST['two'] : '';
$z = (isset($_POST['three'])) ? $_POST['three'] : '';
echo "your something:";
echo $x;
echo $y;
echo $z;
?>
<form name="calculator" method="post">
<INPUT TYPE="RADIO" NAME="one" VALUE="1"> ONE
<INPUT TYPE="RADIO" NAME="two" VALUE="2"> TWO
<INPUT TYPE="RADIO" NAME="three" VALUE="3"> THREE
<input type="submit" value="Submit">
</form>
JS mode:
if(isset($_POST)){
$value= (isset($_POST['value'])) ? $_POST['value'] : '';
$previous = (isset($_POST['previous'])) ? $_POST['previous'] : '';
//play with value and previous one
$x = //your algorithm;
echo "your something:";
echo $x;
?>
<form name="calculator" method="post">
<button type="button" value='1'>ONE</button>
<button type="button" value='2'>TWO</button>
<button type="button" value='3'>THREE</button>
<input name='value' type='hidden' value=''>
<input name='previous' type='hidden' value='<?= (isset($x)) ? $x : ''?>'>
</form>
<script>
$(document).ready(
function() {
$("button").click(function() {
$('input[name=value]').val($(this).val());
$('form').submit();
});
</script>
use php value from click

How to send a form value from a javascript variable and be received as an integer in php? [duplicate]

This question already has answers here:
Set the value of an input field
(17 answers)
Closed 5 years ago.
My form is going to post data to a php called numberActionPage.php. There are two buttons (a +, and a -) around the variable I am trying to post, and they simply change the variable by adding or subtracting one. The problem I'm having is I can't find a way to retrieve the value of my Javascript number variable. Another potential problem I have noticed is that $_POST results in a string in PHP. I am not, however, concerned with negative numbers being posted to the action page, as in the actual program the number will never be lower than 1.
For instance my Javascript looks something like this:
var number = 5;
function subtractNumber() {
number--;
document.getElementById("numberID").innerHTML = number;
}
function addNumber() {
number++;
document.getElementById("numberID").innerHTML = number;
}
My html looks like this:
<form action="numberActionPage.php" method="post">
Number:
<button type="button" onclick="subtractNumber()">-</button>
<a id="numberID"> <input type="hidden" value="5" name="number"> <script>document.write(number);</script> </a>
<button type="button" onclick="addNumber()">+</button>
<br>
<p><input type="submit" value="Submit" /></p>
</form>
My numberActionPage looks like this:
$number = (int)htmlspecialchars($_POST['number']);
echo $number;
Output = 5 on actionNumberPage
So, to reiterate my problem: I need a way for the value="5" part of my input element in my form to receive the value of the javascript variable number. Looking for something such as:
value="<script>retrieveNumber()</script>"
Also, am I preparing the $_POST variable correctly; turning it into an integer properly.
Thanks for your time and advice.
what you want to do is updated the hidden input called number and change its value. so that when submit the value of the input will be sent to the next page like as if it was a normal input. I gave the input an id of 'inputNumber'
Like so
<form action="numberActionPage.php" method="post">
Number:
<button type="button" onclick="subtractNumber()">-</button>
<a id="numberID"> <input type="hidden" id="inputNumber" value="5" name="number"> <script>document.write(number);</script> </a>
<button type="button" onclick="addNumber()">+</button>
<br>
<p><input type="submit" value="Submit" /></p>
</form>
Make changes to your script so that the input value is updated when the buttons are pressed.
function subtractNumber() {
number--;
document.getElementById("numberID").innerHTML = number;
document.getElementById("inputNumber").value = number;
}
function addNumber() {
number++;
document.getElementById("numberID").innerHTML = number;
document.getElementById("inputNumber").value = number;
}

PHP page bookmark with GET

1) Why does the URL show "&submit=Submit" at the end? What should be done to get only the two variables name and age?
2) Does isset function work well with GET method as well? Is there another function or way to handle this?
Result screenshot
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
Name: <input type="text" name="name"/>
Age: <input type="text" name="age"/>
<input type="submit" name="submit"/>
</form>
</body>
</html>
<?php
if ( isset($_GET['submit']) ) { //was the form submitted?
echo "Welcome ". $_GET["name"] . "<br>";
echo "You are ". $_GET["age"] . "years old<br>";
}
?>
The URL is showing variable -> value key pairs. The name= attribute supplies the var name, the element value provides the value. Remove the name= from the submit button. Problem solved.
Yes, isset works with both GET and POST methods.

How to get value of JS promptbox, then pass it to PHP and save it in the database?

I have a home_admin.php file where the user can reject an entry with this code:
echo "
<td>
<a href=changeStatReject.php?id=" . $row['id'] . ">" . "
<img src='media/reject.png'>" . "
</a>
</td>
";
Once the link is clicked, it will direct the user to the changeStatReject.php page with the specific ID of the entry.
My goal is to show a JavaScript PromptBox asking the reason for rejecting before the code is executed.
I use this code:
function MyReason(){
var reason = prompt("Reason:");
document.getElementById("reason").value = reason;
document.getElementById("form").submit();
}
Then I add this to the home_admin.php page:
<form id="form" method="POST" action="changeStatReject.php">
<button onclick="MyReason()">Click Me!</button>
<input type="hidden" id="reason" name="reason"/>
</form>
Even though I get the value from the prompt box, the script for the changeStatReject action is not working anymore.
I think there's a conflict with the <form action="changeStatReject.php"> and <a href=changeStatReject.php?id=" . $row['id'] . ">
Any advice on how to get the prompt box value, save it to the database and at the same time update (reject) the status of the specific entry?
Thanks Mates,
<?php
echo "<td> <a href= "#" onclick='myreason(".$row['id'] . "')>" . "<img src='media/reject.png'>" . "</a></td>";
?>
.............
function MyReason(id){
id.preventDefault();
var reason = prompt("Reason:");
document.getElementById("reason").value = reason;
document.getElementById("id").value = id;
document.getElementById("form").submit();
}
.............
<form id="form" method="POST" action="changeStatReject.php">
<input type="hidden" id="id" name="id" />
<input type="hidden" id="reason" name="reason"/>
</form>
...............
Now you can handle the POST variables in your changeStatReject.php as you want.
add <input type="hidden" name="id" value='id_you_need_to_pass'/> in your form and call changeStatReject.php through this form submit.

Submit multiple inputs through one form and append to array

So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo

Categories

Resources