repopulating $_POST variables transparently in PHP - javascript

So.
In a LAMP stack (PHP), I've got this situation where I'm showing an intermediate page based on some variable from the first page --more simply, I have one page called, say, ListOfProjects, from which I can select a project to view.
When I go to that project, there are other page-navigation elements (like looking at individual jobs in the project, say) the user can click. Once I click them, and am navigated away from the intermediate page between ListOfProjects and IndividualJob, I have to resubmit the data that got me there.
That's fine, and if I could do it automatically, I would. However, I haven't found a way to force this behavior and eliminate the extra click and the ugly "Confirm Form Resubmission" screen.
Does anyone know a way I could A) silently force form-resubmission when the user hits the back button or B) avoid the situation where there's a form that needs resubmitting?
I've thought about trying to just pass that project ID to the session variable, but it's well within scope to have more than one individual project open in the same browser, which would make that unwieldy.
Thoughts? Suggestions?
Thanks!

Don't use POST.
When you are getting data from the server, use GET and put the data in the query string.
POST is designed for sending data to the server that will make a change (e.g. updating data in the database), it isn't appropriate for just deciding what data to look at.

Some solution is bypass using jQuery to resubmit a form when click on back:
<?php if (isset($_POST['ListOfProject'])): ?>
<form method="POST" id="backToProject"></form>
<script>$("#backToProject").submit()</script>
<?php endif ?>
Another solution is to use header("Location: ...") to force users to redirect a page, BUT you should remove all previous $_POST request using unset($_POST) such as:
unset($_POST);
header("Location: your_uri://your_path");
Try reload a page and reload a page using javascript into <script> tag such as:
if ($_POST['ListOfProject'])
{
echo '<script type="text/javascript">location.reload();</script>';
}
Try to understand GET/POST method: https://en.wikipedia.org/wiki/Post/Redirect/Get
And I don't recommended using link of sites using $_POST method such as say Quentin user.

Related

Is there a way to send POST data to another form and return the result of that form?

I need to send form data to another page that will allow the user to do something in a form and return the result of that form back to the original page? Is this possible? I know it's not ideal, but the issue is that I need to make a "drop-in" solution that does not need to be integrated with other code. I know it's a very specific request and scenario.
I know how to send POST data that doesn't require any user input on the processing page. i.e. I can send POST data to 'calculate.php' which will do the math and send it back, but if I need additional user input on 'calculate.php', how can I still send it back?
An example of expected results would be:
Page #1: User enters a number and presses submit to go to next page.
Page #2: User enters a second number and presses submit to finish.
Back to Page #1: User receives sum of both numbers.
Obviously, this is a really redundant thing to do, but I'm trying to simplify the problem as much as possible.
EDIT: There a few restrictions I forgot to add.
Page #1 is not my application, I am developing Page #2 as a "drop-in" solution for Page #1. Essentially, I can only use Page #1 to call Page #2 and receive a response from it. The problem is that I need to be able to allow for user input on Page #2.
I know I can post to Page #2 and then post to Page #1 again, but what if I need to maintain the state of Page #1. For example, if there's an open Web Socket connection.
Please note, I understand that this may be impossible or extremely difficult, but if I don't ask I'll never know right?
You want it with PHP or any other language. If you are running Php on server side then you can use Global variables like $_GET and $_POST.
Page #1: Use Post/Get method to send data to second page.
Page #2: Receive all fields' values using Globe variables ($_GET and $_POST). You can use these values as default values of form fields. Now submit this data to page 1 using post or get method.
Back to Page #1: Here you will receive the data of first page from second page and newly posted data from page 2
Either of these should work:
Never leave the page - use AJAX / XMLHttpRequest to call out to other pages to process chunks of data
Do everything on page 1 using "postbacks" -- the form targets are the same page, there is a state variable like "stage=1", and you use JavaScript to add set hidden variables for any additional state that's needed.
... PHP state validation and processing for the different stages ...
... one or more blocks of HTML for the page (PHP if / else can be used to choose between multiple page views) ...
Edit for added restrictions:
Have page 2 use postbacks or AJAX to collect the additional information
I figured out a few ways to do it.
Update a Database (or Data Store of some sort, depends on security needs) and have Page #1 listen for events from a separate page (on the same server as the database). Very similar to the way PayPal's Instant Payment Notification (IPN) works. I was actually able to set up server sent events with it as well.
Essentially, Page #1 sends data to Page #2 where the user will perform the function and then Page #2 will send POST data to a listener somewhere (either on the same server or Page #1's server), the listener will update a database and Page #1 will be listening or pulling to an event handler that will send an update once the database updates.
Use JavaScript Child/Parent Window functions. This is okay if Page #1 and Page #2 are on the same server, but can get messy and browsers have a lot of restrictions and it varies depending on browser.
Page #1 will open Page #2 in a child window, after the user performs a function, Page #2 will call a function that accepts the result data on Page #1.

Submit a Login form using data received in another form

I have a login form in my webpage. How can I access data in the login form in my webpage and inject the received data in another third party login form which i don't have any end level access and auto-click submit button.
Your question is a little confusing, so let me try to understand:
you are trying to carry the information received from a form throughout multiple ".php" pages?
İf so, you can use the $_SESSION command. More information here, however this is briefly how you can use it.
You start with a
<?php
session_start();
$_SESSION["information"] = informationToCarry;
?>
By opening with a session_start at the beginning of every page, you will be able to retrieve that information with the same syntax
$_SESSION["information"];
Please be a little more clear next time,
Good Luck

Clickable html button counter using php or js

I am very new to php and javascript and I was wondering how I could make a global counter that adds 1 to it every time a user presses a button. The number would stay the same even if someone is on a different computer or refreshes the page. I had this using javascript:
<script type="text/javascript">
var clicks = 0
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()">Click me</button>
<footer>Clicks: <a id="clicks">0</a></footer>
But when ever someone refreshes the page, it resets the number, and it is not global. I tried making something in php which is:
<?php
$clicks = 0
public function clickButton()
{
$clicks = $clicks + 1
}
?>
but I have no idea what I'm doing and how to call the php function or display the php variable.
Your current problem is that your Click variable is only storred on the one computer clicking.
You need to do 2 things:
Store the click variable.
Read the click variable.
(Live updates.)
Store the click variable:
As Vinicius Maia said you need a connection between the users and this can be done with a database, read about MySQL.
Or you can use a more simple method and use php to read and create / write the Click variable into a file named Clicks.txt. See PHP Filesystem Functions on W3C
Read the click variable:
If you chose the MySQL method you should use the commands as so, else if you chose the primitive method you can use the following command: Php File Get Content
Live updates:
To show the variable live and not making your users refresh you should be able to use AJAX so make sure to take a look at that. This question might be usefull.
You should make a interval loop which should constantly check for updates in the variable. This question might be usefull
Together:
Take a good look at Jonas w's answer, he gives a good example on how you could make this and he follows your request. Only downside by using this tactic is that everytime you click you refresh, which might be annoying for some users.
But what he does is:
He reads the variable.
When you click the button he runs the PHP code by opening it.
When done with the code he send you back to index and refresh the side
Repeat...
But for your users, maybe you should add the live function by using this system:
Read the variable.
Make a loop with AJAX that calls a php function that checks and return updates
When you click the button use AJAX to run another php function to update the variable
Repeat...
You have the right JavaScript logic, now you just need to store your clicks somewhere that won't be affected by a browser refresh!
My first suggestion would be to utilize HTML5's localStorage object.
The examples are pretty good on the link. See if you can make something work!
Javascript or PHP will not solve your problem. Just because what you need is some connection between all users that will access your website. For that, you must use some kind of database. I recommend you starting learning MySQL.
Check this: http://php.net/manual/en/book.mysqli.php
The php variables just work inside of one request. So if two people request your site, the script runs twice in two different versions. You have to store the variable on the server.
You could store it into a mysql database ( good articles about that on php.net)
or you could make a counter.txt and edit it with php. ("Fopen" on php.net)
The php runs on the server and cannot interact with the clients side js. You need to send this "button click" to the server. You can do this with AJAX ( google that) or reloading the site and passing gets and posts to the server
Update.php:
<?php
$file=fopen("counter.txt","c+");//open or create counter.txt
$counter=fread($file, 10);//read content
$counter=(int)$counter+1;//add one
fwrite($file,$counter);//save counter
fclose($file);//close file
Header("Location: index.php");//go back to index.php
?>
Index.php:
<?php
$file=fopen("counter.txt","c+");
$counter=fread($file, 10);
fclose($file);
Echo $counter;
?>
Click me
if you need that different users see the same counter, then you will need save the counter in a database.
Regards.

How to set a PHP object in session upon a hyperlink click

I have two PHP pages: One displays the information about an object retrieved from MySQL database and the other allows the user to edit it. The user is transferred from the first page (the view page) to the edit page upon clicking a hyperlink.
I would like to set the information retrieved from the database in session before passing on to the edit page so as to avoid an extra database call. How can I set an object in session upon a hyperlink click event? I know I could append the object as a variable to the GET request but is there a cleaner way than that?
Put the object into the session ($_SESSION['object'] = $object) when the page one loads (or when you retrieve the object from the database). This way you avoid a second call to the database. If you want to place it into the session upon the click event, a second call would be necessary, since you would have to make an AJAX call to a PHP script that retrieves the object. However, this may only make sense if the user is expected to edit that information, otherwise it is just storing data into sessions for no reason, which may also expose security bugs. If your database call doesn't retrieve millions of records, or you don't have hundreds of millions of users editing data in the same time, I can assure you that the impact on the performance by making a second call will go unnoticed.
Adding an object to the session:
$_SESSION['the_object'] = $object;
(Disclaimer: Will not work if the object contains any non-serializable components like closures)
Now when to do it? Actually, you have to do it on the page that shows the data, because if you do it later when the user clicks the edit link, this already triggers a new request which then would again go to the database - you'd have two requests (one for the list, one for the edit).
Generally, the edit link has the ID of the database entry to be edited. But pay attention to carefully check whether the user is allowed to have access or not, because MySQL will simply increment the ID, so it's easy to guess which IDs are valid. Anyone with a tiny bit of clue can modify a HTML form to tamper with IDs.
The approach with the session is somewhat easier: You only allow to edit what has been stored in the session, so the access control has to be done on the list page only.
For those who may be looking for a code snippet to help do this - here it is
Page 1 - this page just loads data from a DB and displays it in a non-editable mode on the screen. On this page we need an Javascript function that can be activated when the hyperlink is clicked
<script language="JavaScript" type="text/javascript">
function processEditLink(){
$.post('process_session_put.php', <?php echo "{S-Object:'".json_encode($obj_)."'});"; ?>
window.location.href = 'edit_object.php';
}
</script>
To explain the above code - we are taking an object (referred to as obj_) and encoding it into the JSON version by using the inbuilt function json_encode. Remember to ensure your object implements JsonSerializable in order to accomplish this. After that we are passing that JSON string as a POST URI parameter via AJAX to a secret page called process_session_put.php. This call is never visible to the end user and happens secretly when the hyperlink is clicked. The secret PHP page will decode the JSON string back into the PHP object and put it in session for all to use. Finally, once that function is complete, the window redirects to the actual edit page that can access data from session and populate the screen.
Next we should modify the hyperlink to trigger this Javascript function when it is clicked as below
<a class="edit-link" href="javascript:processEditLink(this);return false;">[Edit]</a>
Finally - the PHP page called process_session_put.php - which actually does the background work of decoding the JSON string passed to it back into the object format and putting it in session
<?php
if (!isset($_SESSION))
{
session_start();
}
// OBTAIN THE JSON STRING FROM POST URL, DECODE IT AND PUT IT BACK AS A OBJECT IN SESSION
$_SESSION["E-Object"] = json_decode($_POST["S-Object"]);
?>

HTML/Javascript: How to control refresh action without re-submit the form

We are trying to implement a web page that each time of page refreshing will not result in the form resubmit, how to achieve that? Is there any Javascript code or HTML can make it WITHOUT external javascript library(jquery, dojo or extJs)
The reason of such design is that the form is going to tie an unique relation to current data with means cannot do it twice but for security reason we have to use POST instead of GET, also after the action we still want to preserve user the right to do similar action on the same page to another relation. so how to avoid a consequence like that?
Thanks.
Suppose that the action to the form submits it to submit_form.php. That file can handle the data and do whatever it needs to do. Then in it's response, it can redirect the browser to a separate page (you'll have to look up the exact method of how to do this depending on what language you write your POST handler in). This separate page can show the results of the form submit using session variables or some other method.

Categories

Resources