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.
Related
I am using xyz-snippet to insert some php code (post forms and handling post requests) in some Wordpress pages. In the work I am doing it is necessary to take input from a user (with a post form) and process it and redirect them to another page depending on their input. I tried the header() function and it didn't work now I am trying this:
if (empty($entry)){
echo('<h1>I am empty and should be redirecting now</h1>');
$url = 'https://jimmyshapopi.com';
wp_redirect($url);
exit;}
This is not working. I know my logic is fine because that <h1> tag actually prints but the redirect is not working.
XYZ PHP Snippet, uses shortcodes for you to enter you php code into a page. What am I missing?
Thank you to #Sysix and #user3783243 for the answer.
The workaround is to use JavaScript. Echo some JavaScript that changes the window.loaction. The JavaScript code is:
window.location.href = url
Since this needs to be written in the context of a PHP script you need to echo a <script> tag like this:
echo '<script>window.location.href= "' . $url . '";</script>';
In this context the $url variable is defined in the PHP code and not in the JavaScript.
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.
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/\'">';
So hello everyone I have a big problem right now with a button that is made depending on the variables that are sent to the page in this case it's a button the when it's clicked it will access a DB and extract everything in the DB and put it into excel format. The problem right now is when the button is made it always execute the DB search and file making. I know it has to do it because of the way the button is made right now, is there anyway of changing this?
if ($action_db) echo "<button class=\"btn\" onClick='".getUDB()."'>" . DBUser . "</button>";
to this:
if ($action_db) echo "<button class=\"btn\" onClick=\"getUDB()\">" . DBUser . "</button>";
and sending the event trough java-script so it executes the getUDB() method that's on my PHP file?
Thanks.
OK so I went and used part of the suggestion that Sam said and put it on a JQuery and the change is like this
if ($action_db) echo "<button class=\"btn\" id=\"UDB\">" . DBUser . "</button>";
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#UDB").click(function(){
<?getUDB();?>
});
});
OK so the problem is that when I select the clients menu or any other part of the menu to access that part of the webpage it's automatically doing the getUDB method and won't let me access anything else. Any suggestions???
If you don't want the PHP function getUDB() to be called when you load the page, then you're right - you want to move this out into a Javascript function.
By doing echo "foo" . getUDB() . "bar", I'm assuming your page is loading slowly. To solve this, you can use Javascript with an AJAX call. So you probably want to:
Create a separate PHP file that calls getUDB().
Create a Javascript function on your original page that issues a GET request to this new, separate PHP file. It's easiest to do this using jQuery, which makes AJAX requests nice and easy - check out this page.
Write the Javascript needed to handle the response from that page appropriately.
SitePoint has a good tutorial on jQuery and AJAX, check it out.
You need to send a request to the server to initiate anything server-side in response to an event, either by a traditional post-back or via AJAX.
I suggest you make your buttons into forms, substituting the ID of the user for the value of the hidden input:
if ($action_db) {
?>
<form action="/getUDB">
<input type="hidden" name="DBUser" value="<?= DBUser ?>" />
<button class=\"btn\" type="submit"><?= DBUser ?></button>
</form>
<?
}
And then set up a second script to handle POST requests to /getUDB
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