Invoke the browser back button in PHP/Javascript - php

I have a form which sends the user to a different form incase they don't complete it to go back to the form and complete anything that was missed. Now unless the user presses the browser back button the page is loaded fresh which mean any data gets lost.
Pretty much when they come back to the previous page, anything they already filled in should stay intact.
I have the following two pages:
Page 1:
<?PHP
echo "<a href='page2.php'>NEXT</a>";
echo "<input type=text size=25 name=txt />";
?>
Page 2:
<?php
$refer = $_SERVER['HTTP_REFERER'];
$lastlink = "<a href='$refer'>BACK</a>";
echo $lastlink;
?>
On page two if i click BACK to come back to page 1, anything entered in page 1 will be lost which I do not want.
How do I work around it without using Javascript? with Javascript?
I know in javascript I can use
BACK
But is there another way?

Take a look at html5 history api. History api + ajax is great combination

You can also use a session to store $_POST on submit and check if it is set on page-load of the first form.

I am usually satisfied with:
history.back(-1);
Sending back to a previous page using Server-Side logic, is not a good approach to do, so I will disencourage it.

Related

Session variable passing

I've got a php script which builds a html table via echoing data, But i want to add a link onto one of the values and pass that value to the next page.
<td><a href='redirect.php'><?php $_SESSION['WR'] = $row['WorkOrdRef'];echo $row['WorkOrdRef'];?></a></td>
is the line in question but this will only pass the last value added to the table.
Oh, it doesnt work like this. the php code gets executed no matter if you click the link.
I guess the easiest way to do this is to pass it as a get parameter.
html page:
<?=$cellContent?>
redirect.php:
$clickedcell = $_GET['clickedcell']
now the $clickedcell will have the data from the previous page about what cell did the user click.
If you want to use session for some reason, you still have to pass it with GET or POST and store it after the user clicks.
hopefully this is understandable and good luck with your project.
you can change the session by get method also it is possible building by javascript
in the same page add this
if(isset($_GET["clicked"])){
$_SESSION['WR'] = $row['WorkOrdRef'];
$redirect'<META HTTP-EQUIV="REFRESH" CONTENT="0;URL='.$adres.'/"> ';
return $redirect;
}
and then change your url
<td><?php echo $row['WorkOrdRef'];?></td>

I have a short html form with a php for loop which allows the user to build the same form up to ten times on the page

The $i variable is each field and is populated in the 'inp' boxes which are just input boxes and sboxes which are just select boxes. There is only one form when the page loads and it has all the criteria for a trainer to be added. The trainer name would be trainer_name1 on the first form. If they chose to hit the new button they could fill out the information for another trainer, the input box for the second form for 'name' would just be trainer_name2 and all the other fields are named respectively to what they are in the form. As new forms are built in just adds the next consecutive number onto the end of whatever the field might be named.
Here is my code:
<fieldset><legend>Trainer Request</legend></fieldset>
<tr><td><input type='button' onClick="if (show_item(1,10, 0)) { this.style.display = 'none'; }" value='New'></td></tr>
<?php
$contact_array = array('ACCEPTED TRAINING','DECLINED TRAINING','LEFT MESSAGE FOR TRAINING ACCEPTANCE',
'NEED TO CONTACT TO SEE IF INTERESTED',
'NEED PAPERWORK/TRAINING',
'NEED SIGNED CONTRACT AND PAPERWORK',
'NEED TO COMPLETE TRAINING');
for ($i = 10; $i > 0; $i=$i-1)
{
echo "<table id='hidden$i' style='display:none;'><tr>";
echo "<td>Date</td><td>Status</td></tr>";
echo "<tr><td>"; inp("date$i"); echo "</td><td>";
sbox("contact$i", $contact_array, 0, 'wide2');
echo "</td></tr>
<tr><td>Facility</td><td>";
inp("facility$i",50); echo "</td></tr>";
echo "<tr><td>Trainer Name</td><td>";
inp("trainer_name$i",35);
echo "<tr><td>Distance From</td><td>";
sbox("distance_from$i", array('1','2','5','10','15','20','25','30','40','50','60','70','80','90','100'));
echo "</td></tr>
<tr><td>Phone</td><td>";
inp("phone$i",13,'phone');
echo "</td><tr><tr><td>Email</td><td>";
inp("email$i",50);
echo "</tr><tr><td>Address 1</td><td>";
inp("addr1$i",50);
echo "</tr><tr><td>Address 2</td><td>";
inp("addr2$i",10);
echo " City ";
inp("city$i",20);
echo "</td></tr><tr><td>State</td><td>";
inp("state$i",2);
echo " Zip ";
inp("zip$i",'zip');
echo "</td></tr><tr><td>Notes</td><td>";
tbox("notes$i", 40, 3);
echo "</td></tr></table>";
}
?>
<script type='text/javascript'>
show_item(1,10,1);
</script>
As you can see down here I'm building a link which would name the link whatever the trainer name is, in this case trainer_name1 is Tim Jackson, so i've just built a hyperlink with his name.
<?php
// print_r ($_GET);
echo sendback_link($_GET['trainer_name1'], 'ACS/TrainerLookup', 'trainer_id=trainer_code&trainer_name=trainer_name');
?>
I'm confused on how to add a dynamic link like this into the for loop so as the form builds 1 - 10 each trainer_name2, trainer_name3, trainer_name4 etc etc. will have their names hyperlinked.
I'm thinking I create a new variable for the number 1-10 and append it onto the $_GET[trainer_name$].. something like that?
I hope that makes sense and any help would be greatly appreciated.
If I understood your question correctly, you are trying to add more content or replace content on a webpage that has already been generated with PHP.
I think what you are trying to do can be achieved using AJAX.
AJAX is a technique for creating dynamic webpages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
In your case, the process can be described in 3 steps:
the browser making a new request to your server (using javascript)
the server processes the request and sends some information back to the browser
the browser deals with that information (again using javascript) and then updates part of the webpage
There is an example here that shows how you can dynamically change the webpage contents.
Although, if you are allowed to, I would suggest that you use a javascript framework like jQuery which simplifies the whole process (google it for download and instructions on how to use).
You can read about using AJAX with jQuery here and reading the examples that follow to better understand how you can use it.
If you are going to try and use AJAX with jQuery or simply AJAX I suggest that you try it on a test page to get a simple working example, then adding a few things and checking to see if everything works as expected. When the test page is working as expected, import the code to your page.
This is how I would do it, there may be better or easier ways to do it.

Display "Please Wait" between form submission and redirect

I have a page that contains an HTML form that submits back to itself once the user clicks a link in a list of returned search results. Once they click the link, the page takes the submitted variables, runs a bunch of searches on various external APIs, parses a bunch of data, and adds a bunch of stuff to the database, then redirects to a new page that has been created from that data.
All the searching and parsing can take up to six or seven seconds; I'd like to be able to show the user a "Please Wait" kind of message while all that work is happening behind the scenes.
Trouble is, I can't show and hide a DIV because it will screw up my PHP redirect if I've already generated output before the
header('Location: ' . $newURL);
command. I've searched around for answers but while there are many that are similar, none of them are close enough to my specific situation that I can hack around them.
I'd be grateful if someone could point me in the right direction.
Updated version which now works, courtesy #Izkata from his comments below:
jQuery("a").bind('click', function() {
jQuery('#feedback')[0].innerHTML = 'Searching, please wait...';
})
Turned out what I needed to do was assign bind a the message to the click of a link, not to 'submit', as submit was looking for form data.
The simplest way I can think of doesn't require the server to do anything:
<div id='wait_message' style='display: none;'>
Please wait while search is in progress...
</div>
...
$$('.links').observe('click', function(e) {
$('wait_message').show();
});
(Event is written using Prototype.js; you should use whatever is appropriate (JQuery/mootools/etc))
Using the example page in the comments, this works - it runs in Firebug, so just putting it on your page somewhere should work just fine.:
jQuery('#newMovieSearchForm').bind('submit', function() {
jQuery('#feedback')[0].innerHTML = 'Searching, please wait...';
})
There's probably a jQuery-way to update the text instead of using innerHTML, but I don't know it - we don't use jQuery here.
You are right, you won't be able to output data to the screen and then try to redirect afterwards using PHP. You could accomplish this by echoing JS:
echo 'Please wait...';
// Time-intensive PHP here
echo '<script>window.location = "new-location.php";</script>';
You can do something like this:
First, take care of output buffering, i.e. you want php to display output as it executes - you don't want it to buffer.
That way, you can output some html that will show a "loading.." sort of thing.
And, will wait for the script to end it's execution.
Once, you are done with php, redirect using a meta tag, something like:
echo '<meta http-equiv="refresh" content="5;URL=\'http://example.com/\'">';

Call PHP script without changing page

I am trying to make a website that deals with a database of students and tutors. My issue is that so far the only way I know of by which I can run a PHP script (that, for example, removes a user from the database) is putting the information in a link and letting the user click on that link. This does work, but it is annoying because it means that the user is constantly being redirected to new pages. I have also been using some $_SERVER['PHP_SELF']?other information, but this is bothersome because it builds up a long stack of the same page (ie trying to use the Back/Forward function of the browser brings you to the same page).
I would like to be able to generate links/buttons that, when clicked, pass information to a php script without redirecting/changing the page (except possibly refreshing the page to show the new result).
An example from my site, where the page generates a list of all the users and then respective links/buttons to remove each user:
//Gets the list of users and iterates through the data
while ($row = mysqli_fetch_array($data))
{
$fullname = $row['lastname'] . ", " . $row['firstname'];
$username = $row['username'];
$remove_link = "remove_user.php?username=$username";
echo '
<tr>
<td>' . $fullname . '</td>
<td>' . $username . '</td>
<td> Remove this user. </td>
</tr>
';
}
echo '</table>';
When $remove_link is clicked, it loads a php script that removes the user and then redirects back the the original page (user_list.php). Is there a way to just call the remove_user.php script without redirecting/changing pages?
Thanks in advance.
The way websites work today is by using Ajax to dynamically load / change the content of a page.
The best way to use Ajax is to use jQuery's Ajax functions. There are many tutorials on the internet that will show you how to use jQuery.
If you do not want to use jQuery for your Ajax, you can use the old fashioned way of doing it. You can view a tutorial on it on w3schools.com.
Hope this helps!
You need to start familiarizing yourself with javascript and AJAX. Probably look at using jQuery for your javascript framework as it maked this relatively simple and is the most popular such framework, with wide support.
You need to do this via Ajax, one of the easiest ways to do this is with jQuery and its $.ajax, $.post, $.get and $.getJson methods wich will let you do what you want to do.
In case you haven't used jQuery i will recommend you to search for some tutorials especially on nettuts
5 Ways to Make Ajax Calls with jQuery
Read this tutorial, it will help you.
In addition to the answers at the top. In case the user has javascript disabled, I use this AJAX fallback script.
At the end of your deletion script place this:
<?php
//check if the request is not done with ajax
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//now check if the http referer is not empty. It's where the click took place. And if it's not empty redirect back to where the user came from.
if (!empty($_SERVER['HTTP_REFERER'])) {
header("Location: " . $_SERVER['HTTP_REFERER']);
exit;
}
}
?>
Instead of <a href="link"> you can use <a onlick="window.location.replace('link')"> which doesn't add a path into the history and you can use the PHP_SELF approach.
Other than that you would have to use AJAX.

Refreshing page will re-send form data, is it possible to prevent this? (PHP)

I'm creating a form and using it to get data input to send to a MySQL database via php. If someone hits refresh on the page Firefox ressends the last set of information to the php page which in turn sends it to the database. Is there anyway to prevent this?
To fix that problem, there exists Post/Redirect/Get pattern you need to follow :)
Post/Redirect/Get (PRG) is a common
design pattern for web developers to
help avoid certain duplicate form
submissions and allow user agents to
behave more intuitively with bookmarks
and the refresh button.
You need to do a redirect to the same page:
$current_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header ('Location: ' . $current_url);
exit ();
The usual way to do this is to use a redirect.
You get the request, use the data it contains to load your database or whatever, and then perform a redirect (I think you're supposed to use a 303 redirect for this, but I've heard of a lot of people using 302s to avoid certain browser glitches).
The net effect of this is that there was no POST data sent when the redirect occurred, so refreshing can't cause it to be resent and screw up your application/database.
If you don't like any of the above and are using JQUERY. You could do a simple load or ajax function to send the information to your script.
This will erase any chance of duplicate sending and you no page reload. I like this method best, it's fast and easy.
Another solution you can do is have your form send to another page, a bit like this:
<form action="chat_server.php" method="post">
Message: <input type="text" name="message" />
<input type="submit" />
</form>
On the chat_server.php file, you do what you need to do with the data and at the end, you do
echo '<meta http-equiv="REFRESH" content="0; url=chat.php" />';
Give it a try, should get rid of your problem.
Yes. After inserting data you do a redirect.
use a code in a hidden input and this code getting by a table codes for exmaple and if the code sending remove it from database and if the code not set in the table dont accept the query

Categories