Pass php session variables to javascript and back to php - javascript

I have the following code which basically the user enters a number and presses the search button which makes PHP lookup the value and return any records from the MySQL database (approval1.php?go). This works as expected so I left that code out. What I am trying to do is after the user reviews the records they can be approved by clicking the link. That link runs some javascript which takes the number entered from the PHP session. Once the javascript takes the user to the next page which also works I want it to pass that value back to php so that it may be displayed in the next form. How can this be done and also is there a simpler way to do this? Everything I find is either from php to javascript or the other way around. I can't seem to find anything that shows how to get the session variable back.
<!DOCTYPE HTML>
<?php
session_start();
?>
<html>
<head><title>Title</title></head>
</head>
<p><body>
<h3>Search:</h3>
<p>Please enter the reference number of the record you would like to review:</p>
<form method="post" action="approval1.php?go" id="searchform">
<input type="number" name="REF_NO">
<input type="submit" name="submit" value="Search">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function approve() {
passSession("<? echo $_SESSION['REF_NO']; ?>");
$.get("approval2.php");
return false;
}
</script>
Approve Request
</form>
</body>
</html>
</p>

I think what you're looking for is just this: Pass the approval as a GET variable.
Approve Request
Then, in the approval2.php page, receive those GET variables:
$ref_no = $_GET['ref_no'];
$approval = $_GET['approval'];

<?php
session_start();
<?php
<script type="text/javascript">
var vars=passSession("<? echo $_SESSION['session_id']; ?>");
</script>

You can set a hidden input field:
<form method="post" action="approval1.php?go" id="searchform">
<input type="number" name="REF_NO">
<input type="hidden" name="php_sess" value="<?php echo $_SESSION['REF_NO']; ?>">
<input type="submit" name="submit" value="Search">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function approve() {
passSession("<? echo $_SESSION['REF_NO']; ?>");
$.get("approval2.php");
return false;
}
</script>
Approve Request
</form>
So when you submit a form, $_REQUEST['php_sess'] will be populated in php.

I don't think you should use a $_SESSION variable, here. When you lookup something at approval1.php?go and you return some DB records, also return the id REF_NO of that record (e.g. use JSON to send two things at a time). Then, on approval, send this id again, simply by GET. To me, this much more consistent and prevents you from failure e.g. when users browse with two tabs, etc.
Example for approval1.php
<?php
$result = json_encode(array(
"REF_NO" => $id,
"content" => $content
);
echo $result;
?>
Then, access the JSON in Javascript. Use the REF_NO node to prepare your approval link.

Related

Get value of input field using php into variable

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

Auto Submit form just once

I have configured the javascript code to do auto submit but what I want is that if the authentication fails, I do not do the autosubmit again.
My code is the following:
Form:
<?php echo form_open($this->uri->uri_string(), array('class' => 'login-form')); ?>
<div class="form-group">
<label for="email"><?php echo _l('clients_login_email'); ?></label>
<input type="text" autofocus="true" class="form-control" name="email" id="email">
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<label for="password"><?php echo _l('clients_login_password'); ?></label>
<input type="password" class="form-control" name="password" id="password">
<?php echo form_error('password'); ?>
</div>
<?php echo form_close(); ?>
Javascript
<script type="text/javascript">
window.onload=function(){
var auto = setTimeout(function(){ autoRefresh(); }, 100);
function submitform(){
document.forms["login-form"].submit();
}
function autoRefresh(){
clearTimeout(auto);
auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);
}
}
</script>
How can I do it?
I believe your problem lies in array('class' => 'login-form').
Looking at the documentation for document.forms, you access the forms with ID.
I am not familiar with code-igniter; however, your code tells me that you are probably setting the class for a form. You would need to set the id for a form.
For preventing the auto-submit from running twice. From what I see, I suspect that you are getting a normal HTML form at the end. When you submit a HTML form it would make a trip to the server and when it comes back it should reload the page (unless you make it an asynchronous form).
Since the page is reloading, the window.onload would be run every time. To prevent this you would have to use a true-false flag some wheres.
Here are some potential solutions:
You could try looking into accessing url parameters from JavaScript. Some quick searching shows that this is a lot more complex than I'd expect though...
Alternatively, you could move the JavaScript code into a <script> block and echo out a script block from PHP. If you are going with this option you should look into using addEventListener method instead of accessing onload directly. PHP would make it much easier to accessing URL parameters by using $_GET or $_POST.
A second alternative would be to echo out a <input type="hidden"> that holds the true/false value and then access the value using JavaScript.
Once you can use your flag, you just need to check the flag in order to decide whether or not to auto-submit or not.
if (myFlag){
//submit form
}else{
//don't submit form
}
This true-false value is not sensitive data so it should be safe to place it as a GET parameter.

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 form wont submit with javascript

I have a dashboard page, and for the easiest solution I've made the entire page a form (as there are several drop downs scattered across the whole page). I want to implement a feature that can submit the form every 30 minutes, be it with JavaScript, jQuery or anything else, but when I've tried it just refuses to execute the code, so I tried going back to something basi such as submitting the form when the drop-down is changed via "OnChange".
Here is an example snippet of a seperate page with some code from my dashboard page. This in itself should be working but I just can't see why it won't execute the code, maybe I'm missing something obvious? Can you help me fix this:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function submit_my_form(myfield)
{
myfield.form.submit();
}
function submitForm() {
document.getElementById("branchForm").submit();
}
</script>
</head>
<body>
<?php
$branch_array = array(
array(1,"BRANCH 1",1, "http://BRANCH.BRANCH1:1"),
array(2,"BRANCH 2",1, ""),
array(3,"BRANCH 3",3, "http://branch3:3"),
);
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST" name="branchForm" id="branchForm">
<select name="query" id="query" class="select" onChange="submit_my_form(this);">
<?php
foreach ($branch_array as $x) { // populate select box with branches available from array
echo '<option value ="'.$x[0].'"';
if (isset($_POST['query']) && $_POST['query'] == $x[0])
{
echo ' selected="selected" >'.$x[0].". ".$x[1].'</option>';
} else {
echo ' option="'.$x[0].". ".$x[1].'">'.$x[0].". ".$x[1].'</option>';
}
}
?>
</select>
<input type="submit" name="submit" value="Refresh" class="btnRefresh" />
<input type="button" value="go" name="click" onClick="submitForm();" />
</form>
<?php echo "<br/>Output: {$_POST['query']}"; ?>
</body>
</html>
Nothing happens when the drop-down is changed, and nothing happens when the "go" button is pressed.
Since you don't mind using jQuery, here you go:
var form = $("#formId");
$("select[name=selectField]").on("change", function(e){
form.trigger("submit");
});
http://jsfiddle.net/zt8zz1j5/
All it essentially does is listen for change on the select element, and simply triggers the submit event on the form. Of course you'll need to change the names and IDs to fit your code, but I'm sure you can handle that :), and remember to include jQuery in the document.
And for the button it's the same thing. You listen for the 'click' event and then trigger 'submit' on the form.

enabling and disabling a button using javascript and php

hi i really dont know a lot about javascript so sorry for this amatuer question.
im trying to make a quiz page using php with 2 sets of questions. i want to disable the 2nd button for the other quiz and only be enabled when the user passed the first one.
this is what i wanted to happen:
<?php
require 'config.php';
$name = "kevin";
$result =mysql_query("select score from members where Username = '$name' " );
?>
<input name="button1" type="button" value="1" />
<input name="button2" type="button" value="2" disabled="disabled" />
<script type="text/javascript">
if<?php $score is greater than 5 ?>{
$('#button2').removeAttr('disabled');
}
else {
$('#button2').attr("disabled","disabled");
}
});
</script>
any help will be much appreciated, thanks in advance.
You're trying to mix PHP and JavaScript, you can't do that. They run on completely different machines at completely different times.
Since the score is known server-side (in PHP) before the page is even sent to the client, make the conditional happen in the PHP code and only emit to the client the markup that you want. Something like this:
<?php
require 'config.php';
$name = "kevin";
$result =mysql_query("select score from members where Username = '$name' " );
?>
<input name="button1" type="button" value="1" />
<?php
// use a real conditional, I'm just duplicating you for simplicity
if ($score is greater than 5) {
?>
<input name="button2" type="button" value="2" />
<?php
} else {
?>
<input name="button2" type="button" value="2" disabled="disabled" />
<?php
}
?>
There's no need for JavaScript at all in this case, since the logic is all server-side.
Now you can still use JavaScript for more client-side interactions of course. Also, be aware that this isn't really any kind of security measure to prevent users from clicking on the button. Any user can modify the HTML/JavaScript being sent to them and still click on the button if they really want to. So if you need to prevent the user from doing something then that would need to be done server-side as well, in response to whatever action the user should not be authorized to perform.
You can try like this
if($score > 5){
?>
<script>
$(document).ready(function(){
$('#button2').removeAttr('disabled');
});
</script>
<?
}else{
?>
<script>
$(document).ready(function(){
$('#button2').attr('disabled');
});
</script>
<?
}
or if removeAttr/attr are not working then you can do like this
$('#button2').prop('disabled', false);
$('#button2').prop('disabled', true);

Categories