Get value of input field using php into variable - javascript

I have already refered to this question and the accepted answer did not work for me: How to get input field value using PHP
This is my code result.php file:
...
<th>
<form name="form" action='checkout.php' method='POST'>
<input class='mx-2' type='number' id='price' name='price' placeholder='Donation Amount'">
</form>
</th>
<script
src='https://checkout.stripe.com/checkout.js' class='stripe-button'
data-key='key'
data-amount=get value of input field with id price here
data-name='Name'
data-description='Description'
data-currency='usd'
data-locale='auto'>
</script>
...
I have also tried fetching the value of the input like this and then using that variable:
<?php $price = isset($POST['price']) ? $POST['price'] : 0; ?>
Another method I tried:
<?php
$htmlEle = "<span id='SpanID'>Span Sports</span>";
$domdoc = new DOMDocument();
$domdoc->loadHTML($htmlEle);
$spanValue = $domdoc->getElementById('SpanID')->nodeValue;
I found the above snippet on https://phpcoder.tech/how-to-get-html-tag-value-in-php/ and modified it as per my need but did not work.
How can I do this? My app is pay what you want so I want the price to be filled in by the user on the client side.
I am open to different approaches and solutions to the one I asked for.

If you don't want to wait for the client to submit the form, you will need some javascript as PHP is a server-rendering language.
Basically you would need to set-up a listener on the input and after the client types the data in a format you want and you validate it, you can pass that to stripe script.

<th>
<form name="form" action='checkout.php' method='POST'>
<input class='mx-2' type='number' id='price' name='price' placeholder='Donation Amount'">
<input type="submit">
</form>
</th>
submit button in missing here, so add a submit button.
And update your PHP code
<?php $price = isset($_POST['price']) ? $_POST['price'] : 0; ?>
$_POST - is PHP Superglobals for getting form's post values.
$POST (which you are using) is a normal PHP variable.
Please update your code like this.It will works.

You have used the wrong POST syntax, the correct is: $_POST, while you are trying get: $POST.
The docs: https://www.php.net/manual/en/reserved.variables.post.php
--In JavaScript part--
If you want to handle PHP the price before call Stripe, you should use other configuration, because this one will not work anyway.
You can:
call Stripe on like ajax or other request that in background post the forst
call Stripe on other page
don't do form, just plain text field (if you don't need PHP, handle price before Stripe request)
It depends what you want to do.

I used a different method to solve the problem. I put the text box on a separate page and the pay button on the checkout page, so I am passing the price from the previous page to the checkout page now and accessing it using query parameters

<form name="form" action='checkout.php' method='POST'>
<input class='mx-2' type='number' id='price' name='price' placeholder='Donation Amount'">
<button name="submit" type="submit" >submit button</button>
</form>
///in checkout.php code
if(isset($_POST['submit']){
$price = $_POST['price'];
echo $price;
}
///I hope this would work

Related

Submit form and redirect not working

EDIT: I should mention the form submits fine manually but with the javascript nothing seems to happen
I'm trying to get a form to autosubmit on page load and then redirect the user. Reason for this is this is part of a PHP page and the data needs to go into my database but then also POST the variables to a 3rd party SMS platform then return to the users dashboard.
My form looks like this:
<html>
<form action="https://www.example.com" id="myForm" method ="POST">
<input type="hidden" name="apiKey" value="withheld">
<input type="hidden" name="message" value="<?php echo $club_name ?> have requested you to play for them this weekend. Please login to your account to see more information and accept.">
<input type="hidden" name="to" value="<?php echo $to ?>">
<input type="hidden" name="from" value="withheld">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</html>
This seems to work fine so I assume the Javascript is incorrect which is:
<script>
document.getElementById('myForm').submit();
window.location.replace("https://www.example.com");
</script>
You have to use a different name than
name="submit"
as all name attributes are set as properties on the form,
hence overriding the default "submit" property on the form,
and the default form method "submit()" is gone.
https://developer.mozilla.org/de/docs/Web/API/HTMLFormElement
"Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's action HTML attribute)."
In your code window.location.replace("https://www.example.com"); line won't make sense because submit() function will try to submit the form and will change the page and then replace function will prevent submitting the form and will redirect the page. The right way to do this via js can be, submit the form via ajax and in the success callback of Ajax run document.getElementById('myForm').submit()

Targetting button outside of a form in action.php?

I currently have 2 forms, which adds data to my database. They both work, but they each have their own submit button - and I only want one submit button to collect the data from all the forms.
I found some javascript that should set the deal;
$("#submitbutton").click(function(){
$("#form1").submit();
$("#form2").submit();
});
The button I'm targetting is outside of both forms and looks like this:
<input id="submitbutton" type="button" value="add">
I'm pretty sure the reason why it doesn't work, is because of the way my php is written. I'm targetting the submit button in each form to excecute the php.
You can see the forms and php below.
One of the forms allows you to upload a picture;
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
The action file contains this php;
<?php
if(isset($_POST['sumit']))
{
if(getimagesize($_FILES['image']['tmp_name'])== FALSE)
{
echo "Please select an image.";
}
else
{
$image= addslashes($_FILES['image']['tmp_name']);
$name= addslashes($_FILES['image']['name']);
$image= file_get_contents($image);
$image= base64_encode($image);
saveimage($name,$image);
}
}
displayimage();
function saveimage($name,$image)
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="insert into pictures (name,image) values ('$name','$image')";
$result=mysql_query($qry,$con);
if($result)
{
//echo "<br/>Image uploaded.";
}
else
{
//echo "<br/>Image not uploaded.";
}
}
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="select * from pictures";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
mysql_close($con);
}
?>
The other form lets you choose between multiple categories collected from my database;
<form id="form2" action="checkbox.php" method="post">
<label for="Category">Category</label>
<br />
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="checkbox" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
<input type="submit" name="Submit" value="Submit" class="btn btn-default"/>
</form>
And has the following php;
<?php
include("config.php");
$checkbox = $_POST['category'];
if($_POST["Submit"]=="Submit")
{
for ($i=0; $i<sizeof($checkbox);$i++) {
$query = "INSERT INTO placecategory (category_id) VALUES ('".$checkbox[$i]."')";
mysql_query($query) or die(mysql_error());
}
echo "Category is inserted";
}
?>
I've tried targetting the new button I made that should excecute the javascript, but it doesn't seem to work because that button is out of the form.
Is there a way to target the button outside of the form so the php excecutes when that is clicked? Or how can I rewrite this?
Any help is appreciated!
Not sure I understand completely what you're trying to do but try this with HTML5 add form="form1" and form="form2" for your second one and let me know if this works.
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
<input type="submit" name="sumit" value="Upload" form="form1" />
Taking in account your complementary comment, then your proposed javascript sequence would work, assumed you have:
suppressed buttons such as <input type="submit"... /> from both forms
added the new button <button name="submitbutton">...</button> outside of the forms
modified the PHP parts accordingly, referencing $_POST['submitbutton'] instead of sumit and Submit respectively
You didn't report how it currently don't work, so the above steps target only the changes precisely related to the fact you replace two in-form buttons by a unique out-form one.
But something may turn wrong elsewhere. I notably noticed the non-usual way (at least for me) you get and process the image. Also you must ensure that your javascript part have really been executed.
Let me know if it doesn't work yet, than adding precise description of what turns wrong.
Edit, based on your provided comments and live preview.
Fully testing is not really possible because the server PHP part is out of reach, bue we can use Firebug to debug JS part.
So adding a breakpoint we can observe that, as soon as $("#form1").submit(); has been executed, the server returns a new page with the "Place has been added!" message.
In the other hand, without any breakpoint set, the server returns returns a new page with the "Categorie inserted!" message.
Though the OP didn't show the addingplace.php part of the current live preview, and comparing with the checkbox.php part, we can guess that:
In the reduced execution part, the first step addingplace.php did work as expected.
What we observe while whole execution merely means that all three parts have worked as expected, but each one having its returned message overwritten by the next one, but for the last one.
In other terms, when you comment "it only seems to submit the last form", this is a false impression based on what you only can see.
To ensure this is true or not you should control what is really updated or not in your database.
Let me know.
That said, it must be noted that this illustrates how the couple server-browser works in those circumstances: as already pointed by #David in a comment under the OP, to submit a form causes the browser to immediately receive a new page which overwrites the current one.
In the current example, it works because there are only few forms, and all three are submitted in a very reduced time, almost instantly: so the 3rd submit() can get executed before the 1st one's returned page comes.
So the recommended way to achieve the whole work in your example is merely to use only one form, with its unique submit button. BTW I wonder why you wanted to have this more complicated structure with three forms: what is the expected benefit?
Last point, outside of the precise issue you reported: you should pay attention to how you're coding. There is a lot of inconstencies in the HTML part, e.g.: a <html><body> part inside the already existing <body>; an exotic <br></br>; also you kept a supplemental button in the 1st form.

PHP: Using $_POST to display form values

I have a basic HTML form with one input text field, along with a submit button. Now, I want to use JavaScript to display the content entered by the user in the text field after form submission.
Here's the code of my form:
<form method = "POST">
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" onclick = "postResul()" />
</form>
On clicking the submit button, the postResul() function is called:
<script>
function postResul()
{
var htmlString="<?php echo $_POST['tweet1']; ?>";
alert(htmlString);
}
</script>
Now, both these code snippets are stored inside a PHP file. However, on submitting the form, the data entered in the input form field doesn't get displayed. I'm displaying the $_POST['tweet1'] variable in order to display the entry submitted by the user.
What seems to be wrong here? Am I using the $_POST variable in PHP the wrong way?
If you want to display the input's value BEFORE sending it to your server:
document.querySelector("form").addEventListener("submit", function()
{
var value = this.querySelector("input[name='tweet1']").value;
alert(value);
return false; //disable sending the data to the server
}, false);
<form id="myForm" method="post" action="index.php">
<input type="text" name="tweet1" />
<br>
<input type="submit" />
</form>
If you want to display the input's value AFTER sending it to your server:
<form method="post" action="index.php">
<input type="text" name="tweet1" />
<br>
<input type="submit" />
</form>
<?php echo htmlspecialchars($_POST["tweet1"]); ?>
These are different things. You can use $_POST only after you've sent some datas to the server. When you open yoursite.com/index.php in your browser, you make a HTTP GET request. In this case, $_POST will be an empty array, since it's a GET request, no data is sent to the server. When you submit the form, you make a HTTP POST request. Your PHP can access only that data you sent to the server. With Javascript, you work on the visitor's computer, not on the server. The only one way to send the data to the server without refresing the page, if you use AJAX, and make a new HTTP POST request, that'll run in the "background". But you do not need this if you just want to display the input's value, and you don't want to save it on your server. That can be done with Javascript, and without PHP.
The code you posted above would work like this:
You make a HTTP GET request to yoursite.com/index.php.
No data is sent to the server, $_POST will be empty.
var htmlString="<?php echo $_POST['tweet1']; ?>"; In this line, you try to echo an non-existing member of $_POST, you might see an error if display_errors is not disabled.
You click on the submit button.
It has an onclick attribute, postResul (a Javascript function) is called. If you open the page's shource, you'll see this:
function postResul()
{
var htmlString="";
alert(htmlString);
}
After an empty popup is shown, and you press OK, the browser send the data to your server, and you'll able to acess the input's value via $_POST.
If you press the submit button again, you'll see submited value (and not the input's actual value), because if you open the source code, you'll see this:
function postResul()
{
var htmlString="entered data";
alert(htmlString);
}
But that isn't want you want, so see the examples above depending on what you want (save the data, or just display it in the browser).
This should work:
function postResul()
{
var htmlString=document.getElementsByName("tweet1")[0].value;
alert(htmlString);
}
But you should really read more on how client-side and server-side languages work.
You cannot use $_POST['tweet1'] to get the value when you are invoking a Javascript function. Basically client side and server side are totally different.
You can obtain the result using Javascript as:
function postResul()
{
var htmlString= document.getElementsByName("tweet1")[0].value;
alert(htmlString);
}
In HTML:
<form method = "POST">
<input type = "text" name = "tweet1"/>
<br>
<input type = "submit" onclick = "postResul()" />
</form>
Note: The above function runs in client side and not in server side.
$_POST can be used to get values of the submitted form in a php page.
Cheers.
You have to make another file. Change your code to:
<form method="POST" action="another.php" >
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" />
</form>
In file another.php you can show the variable then:
<?php echo htmlspecialchars($_POST['tweet1'], ENT_QUOTES, 'UTF-8'); ?>
You should use the form in a different way
<form method="POST">
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" />
</form>
test.php file
<?php
return json_encode([1, 2, 3]);
js
$('form').on('submit', function() {
$.post('test.php', {}).done(function(response) {
alert(response);
})
})
Something like this.
Hope it's useful.
if you are using jquery library you can do this
<form method="POST">
<input type = "text" name = "tweet1" class="tweet" />
<br>
<input type = "submit" class="submit" />
</form>
$('.submit').click(function(e){
alert($('.tweet').val());
e.preventDefault();
});
jsfiddel working example http://jsfiddle.net/mdamia/j3w4af2w/2/

Get Input Value on the same page with PHP?

Well, first i'm new in PHP. Is there a way to get the input value from a existing input on the page on page load with php and pass it to a variable?
For example i have this input: <input type="text" name="g_id_p" id="example1" value"foo">
I want to do something like this: $got_it = $_GET['g_id_p'];
Sorry again if i wrote my code wrong, im noobie on this. Hope to someone help me.
First, would be great to know what method is the form. (GET or POST)
Then after know what type of method you could call it in PHP:
METHOD POST:
<input type="text" name="g_id_p" id="example1" value"foo">
$variable = $_POST['g_id_p'];
METHOD GET:
<input type="text" name="g_id_p" id="example1" value"foo">
$variable = $_GET['g_id_p'];
If you haven't defined a method, in html the tag for a form is:
<form>
<!-- Here goes your input and some stuff -->
</form>
Then it would be something like:
<form name="form_name" class="form_class" id="form_id" method="TheFormMethod" action="ThePageThatExecutesThisForm">
<!-- Here goes your input and some stuff -->
</form>
TheFormMethod can be post, get, delete, put.
You can't really get an associated value of an input tag within the same PHP page but what you can do is set the value of a variable beforehand.
What I mean is, create an array that will store all the values of all the input tags.
$inputValues = array();
$inputValues['g_id_p'] = 'foo';
Then when you have the tag later on just echo it from the PHP var.
<input type="text" name="g_id_p" id="example1" value="<?php echo $inputValues['g_id_p']; ?>">
As you can see, we aren't really 'getting' the value that you set but the end result is the same.
You have to check if the values is set isset(), where you want to use the variable do:
if(isset($_GET['g_id_p'])){
//your code
}

ajax display text on submit

I have a simple form with a submit button (below). I am trying to let the user type in the text box then when he/she clicks submit the page will refresh and echo out what they typed in a div. The data the user types is stored in a database before being echoed. The problem is that when I click submit, the input doesnt show immediatly. I have to click refresh for it to show and when I do my browser gives me a popup (safari) asking to resend the data. This will result in duplicate data inserted in the DB. I have a feeling I need to use javascript and I could also make it more elegant with a fadeIn, but I dont know how to do that. I guess I'm asking if there's a way to use javascript to take a user's text and insert it into a mysql DB and also display it after submit is clicked all on 1 or 0 (prefereably) refreshes. thanks
Here's my code:
<form method='POST' action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>
<?php
$input=$_POST['text'];
$put=mysql_query("INSERT INTO table VALUES ('$input')");
echo "<div id='area'>";
//i connect to the DB and echo out the data here
echo "</div>";
?>
I would put the php statements before you're actual html code and would modify you're code like this
<?php
if (isset($_POST['text']))
{
$input = mysql_real_escape_string($_POST['text']);
$put=mysql_query("INSERT INTO table VALUES ('$input')"); //At this point the info has been put inside the DB
echo "<div id='area'>";
//i connect to the DB and echo out the data here
echo mysql_query("SELECT * FROM table");
echo "</div>";
}
?>
<form method='POST' action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>
The reason why you don't see it is that the HTML is loaded before you php I think. So I would do a php page where all the sql treatement would be done and once that is done recal you index.php and in there query you're information from the database.
Setting aside SQL injection attacks your code is vulnerable with, the standard practice is to respond to the POST with a redirect back to where the form was. In your case, it will be the page which runs SELECT from table.
No need to use AJAX here. Just make sure that you do one of the following:
Make sure you SELECT from the DB after you have INSERTed the data.
Better, is that if ($_SERVER['REQUEST_METHOD'] == 'POST'), then rather than performing an extra SQL query, just display the POSTed value since you already know it.
A side note on your code sample. If you don't have magic_quotes enabled, it's susceptible to SQL injection, so make sure you properly escape user input before using it in queries.

Categories