I have a textbox that allows users to search my website.
<form method="post" action="">
<input type="text" name="search" id="search" />
<input type="submit" name="submit" id="submit" value="Search" />
</form>
Upon the user clicking the "Search" button, how do create the following URL, and append the contents of the search box to end, whilst adding "_" in replace of any spaces?:
http://www.mysite.co.uk/find/this_is_my_search
Also, if somebody edits the search query in the URL, how do I update the search textbox to reflect this change, so the box contains the following
this is my search.
You need to handle that url using you 404 page. You can use $_SERVER['REQUEST_URI'] to get that path. For instance you could do this in your custom 404 page:
<?php
if (stripos($_SERVER['REQUEST_URI'], "/find/") == 0) //If url is yoursite.co.uk/find/
{
$searchterm = basename($_SERVER['REQUEST_URI']);
//Search for $searchterm
//Print the results
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You can change action URL with JavaScript before submit event.
You can Use onSubmit event or use jquery
$('form').submit(function(){
$(this).attr('action', $('#search').val().replace(' ', '_'))
})
Change form method to get.. And also if you're using code igniter or other framworks you should be able to code like
$search = Uri:segment(2);
echo '<input type="submit" name="submit" id="submit" value="'.$search.'" />';
This can be achieved several ways.
Javascript
See StarLight's answer. It's simple and does the job, but you need to check for illegal URL-characters.
PHP redirect
Example: Set form action to 'search.php'.
<?php
$urlstr = urlencode(str_replace(' ', '_', $_GET['search']));
header("Location: http://www.mysite.co.uk/find/$urlstr");
exit;
?>
To update the textbox you need the following code on the page showing the search box.
<?php
// First get $urlstr from url.
$searchstr = str_replace('_', ' ', urldecode($urlstr));
$textboxvalue = (empty($searchstr)) ? 'Search' : $searchstr;
?>
<input type="submit" name="submit" id="submit" value="<?=$textboxvalue?>" />
Related
I have some numbered pages:
1.php
2.php
3.php
etc.
I want to create a textbox that the user enter any number: 2 for example, and hit enter or Go button, and they will go to the page 2.php depending on the number entered.
I know how to link to a specific page as in form action="....", but I am not sure how to echo the user input and translate it as link (whether using html or php).
Ex:
<form method="POST">
<input type="number" value="" />
<input type="submit" value="Go" />
</form>
You need to add an action attribute to your form and a name attribute to your number input. The file from your action attribute will "catch" the POST variables and do the logic needed to redirect your user. Change your form tag to:
<form method="POST" action="redirect.php">
<input type="number" value="" name="redirect" />
<input type="submit" value="Go" />
</form>
Then create the redirect.php file that gets the POST variables and does the redirection:
<?php
$redirectPage = (int) $_POST['redirect'];
$redirectUrl = "http://www.example.com/{$redirectPage}.php";
header("Location: $redirectUrl");
printf('moved.', $redirectUrl);
Beware that there's no input validation nor error handling included.
I think, the best available option in your case would be the one using client-side javascript to dynamically change the form's action attribute base on the number entered in the input box.
A quick and dirty solution to fulfil such a task might look like this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function submitAction(formElement) {
var // get the input box element
el = document.getElementById('form-action-number'),
// get a number specified by user in the input box
num = parseInt(el.value),
// validate that it's really a number and is greater than zero
// (you don't want someone to request -666.php right? :)
// build a page url using the correct number
page = !isNaN(num) && num > 0 ? num.toFixed(0).toString() + '.php' : undefined;
if (page) { // the page url is valid
// set form's action attribute to an url specified by page variable
formElement.setAttribute('action', page);
// returning true will allow the form to be submitted
return true;
}
// you might think of a better way to notify user that the input number is invalid :)
console.error('INVALID NUMBER SPECIFIED!');
// returning false will prevent form submission
return false;
}
</script>
</head>
<body>
<!-- When user clicks Go, the return value of submitAction function will be used to decide if the form should be submitted or not -->
<form method="POST" onsubmit="return submitAction(this)">
<input id="form-action-number" type="number" value="" />
<input type="submit" value="Go" />
</form>
</body>
</html>
With PHP you can do something like this:
<?php
// Check if the POST value has been set
if(isset($_POST['my_number'])) {
// Redirect to the corresponding page
header('Location: ' . $_POST['my_number'] . '.php');
}
?>
<form method="POST">
<input name="my_number" type="number" value="" />
<input type="submit" value="Go" />
</form>
This is like DaMeGeX's answer but uses javascript to go to the new page.
<?php
// Check if the POST value has been set
if(isset($_POST['my_number'])) {
// Redirect to the corresponding page
echo "<script> window.location.href = '".$_POST['number'].".php' </script>";
}
?>
<form method="POST">
<input name="my_number" type="number" value="" />
<input type="submit" value="Go" />
</form>
I am trying to create a query screen for reports. I have created a php code by getting support from here and other sites. But the problem is; when a user input report serial number and submits it, the page only reload. After reload; when the user enters serial again to the field and hits submit, this time the code works but only for the 1st serial entered, no matter the second serial is.
I have tried to change the parts of my code but could not find a solution.
I am trying to create a system like, user will enter a serial to the field and when hits to submit button; a new window pop out and directs user to a link which has been created based on user input.
For example, user entered "234" as the serial number and hit submit button. The new window will go to the; "example.com/reports/report234.pdf"
Here is the code I have problem with;
<?php
if(isset($_POST['submit']))
{
$seri = $_POST['seri'];
$url = "https://www.example.com/wp-content/uploads/Rapor/".$seri.".pdf";
}
?>
<form method="post" action="<?php echo $url; ?>">
<input type="text" name="seri"><br>
<input type="submit" name="submit" value="Sorgula"><br>
</form>
That's because you're setting the redirect $url as the form action. That results in the following:
Form action is empty, thus the form will be sent to the page itself
The serial number and the $url is created and set as the form action
Now when the user submits the form again it will be directed to the $url set, regardless of what he has filled in the seri field this time
Here is an example of a more correct approach to your problem:
<?php
if(isset($_POST['submit']))
{
$seri = $_POST['seri'];
Header("Location: https://www.ozguncicek.com.tr/wp-content/uploads/Rapor/$seri.pdf");
}
?>
<form method="post">
<input type="text" name="seri"><br>
<input type="submit" name="submit" value="Sorgula"><br>
</form>
Note there's no need to set an action to the form since you're going to redirect the user when he submits the form.
Another important point is checking if seri isn't empty before redirecting the user. That could be accomplished as simple as:
<?php
if(isset($_POST['submit']) && $_POST['seri'])
Redirect after form submit,
<?php
if(isset($_POST['submit']))
{
$seri = $_POST['seri'];
$url = "https://www.example.com/wp-content/uploads/Rapor/".$seri.".pdf";
header("Location: ".$url);
}
?>
<form method="post" action="<?php echo $url; ?>">
<input type="text" name="seri"><br>
<input type="submit" name="submit" value="Sorgula"><br>
</form>
I am using a form and the 'get' method to offer users a return option to an unknown url that they came from within my site, as per the code below. I prefer this to just the browsers back button and it works without javascript.
The problem I am having is that some browsers (chrome, safari, there may be others) are adding a question mark to the end of the url they are referred back to. I don't want this for seo reasons.
My question is either:
1) Can I prevent the question mark within my php code somehow; or
2) Please could somebody show me how to redirect the url using htaccess, I potentially have urls that could end:-
.html?
.htm?
.php?
/?
Thanks in advance.
<?php
if (isset ($_SERVER['HTTP_REFERER']) ) {
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo '<br /><form action="' . $url . '" method="get">
<div id="submit"><input type="submit" value="Return to previous page" /></div>
</form>';
}
?>
The ? probably gets added because you're doing a GET request from a form.
Why not do something like:
<input type="button" onclick='document.location.href=<?php echo json_encode($url);?>'>;
use POST method instead of GET
Is it pertinent that you use a form for this? Why not use a hyperlink and style it to look however you want with CSS?
You could use try using a button instead of creating an input value that will be passed.
<form action="url" method="get">
<button type="submit">Return to previous page</button>
</form>
Instead of posting to random URLs (which is not really a good idea) consider using redirects
A solution would be
<?php
if (isset ($_SERVER['HTTP_REFERER']) ) {
$url = htmlspecialchars($_SERVER['HTTP_REFERER'],ENT_QUOTES,'UTF-8');
echo '<br /><form action="redirect.php" method="get">
<input type="hidden" name="return" value="'.$url.'">
<div id="submit"><input type="submit" value="Return to previous page" /></div>
</form>';
}
?>
then in redirect.php
<?php
if (isset ($_GET['return'] ) {
$url = $_GET['return'];
header('Location: '.$url, true, 303); // or 302 for compatibility reasons
echo 'Continue';
exit;
}else{
echo 'Error, no redirect specified';
}
you can replace action="GET" and $_GET with action="POST" and $_POST and it will work the same.
or simply
if (isset ($_SERVER['HTTP_REFERER']) ) {
$url = htmlspecialchars($_SERVER['HTTP_REFERER'],ENT_QUOTES,'UTF-8');
echo 'Return to previous page';
}
both will still create a new history entry in the browser.
In the htaccess you should have something like this:
RewriteEngine on
RewriteRule ^myPage-([a-zA-Z0-9_]*).html myPHPfile.php?var=$1
By the above piece added to your htaccess, when a URL like myPage-whatever.html is called, it's just like calling myPHPfile.php?var=whatever
It is very difficult for me to put in words my query. But I will try.
I have a site xyz.com which has search facility for listed products. The search page url is generated like this :www.wyz.com/search/search_term
I want to create a iframe page in a third party site with a search facility which can directly communicated with my site xyz.com.
I have tried to create a search box with a submit button. I want to append the search query in as a variable to my form action url string.
So the search string should look like this :www.wyz.com/search/my_string_variable
The code I have written is:
<?php
$url='http://www.xyz.com/search/';
?>
<?php
if (isset($_POST['submit']))
{
$r1=$_POST['num1'];
}
?>
<?php
$result=$url.$r1
?>
<html><body>
<form action="<?php echo $result; ?>" method="post">
Num1:<input name="num1"><br>
<input type="submit" name="submit">
</form>
</body></html>
==================================================================
But output what I get, is only "http://www.xyz.com/search/". It removes my variable from the url. I am not able to find what is the reason? I have also tried to print result via to check the actual output and it shows that it has added the value at the end of url. But when I want to achieve the same thing via form action it does not work. please help?
<?php
$url='http://www.xyz.com/search/';
?>
<?php
if (isset($_POST['submit']))
{
$r1=$_POST['num1'];
$result=$url.$r1;
header("location:$result");
}
?>
<html><body>
<form action="" method="post">
Num1:<input name="num1"><br>
<input type="submit" name="submit">
</form>
</body></html>
Please try the above code. I have made some modifications. The main reason your code is not working is whenever you press the submit button it is going to the the url "http://www.xyz.com/search/" directly .The if condition is never executed. In the above mentioned code it will work properly
action="" - you are submitting to the wrong url. Here is alternate version -
<?php $url='http://www.xyz.com/search/';
if (isset($_POST['submit'])) {
$r1=$_POST['num1']; header("Location: ".$r1); // 302 redirection
}
?>
<html><body> <form target="_SELF" method="post"> Num1:<input name="num1" type="text" /><br /> <input type="submit" name="submit" /> </form> </body></html>
I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/
The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.
<form method="POST" action="mlml/process.php">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="submit" value="" id="submit"name="submit" >
</form>
You will need AJAX to post the data to your server. The best solution is to implement the regular posting, so that will at least work. Then, you can hook into that using Javascript. That way, posting will work (with a refresh) when someone doesn't have Javascript.
If found a good article on posting forms with AJAX using JQuery .
In addition, you can choose to post the data to the same url. The JQuery library will add the HTTP_X_REQUESTED_WITH header, of which you can check the value in your server side script. That will allow you to post to the same url but return a different value (entire page, or just a specific response, depending on being an AJAX request or not).
So you can actually get the url from your form and won't need to code it in your Javascript too. That allows you to write a more maintanable script, and may even lead to a generic form handling method that you can reuse for all forms you want to post using Ajax.
Quite simple with jQuery:
<form id="mail_subscribe">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="hidden" name="action" value="subscribe" />
<input type="submit" value="" id="submit"name="submit" >
</form>
<p style="display: none;" id="notification">Thank You!</p>
<script>
$('#mail_subscribe').submit(function() {
var post_data = $('#mail_subscribe').serialize();
$.post('mlml/process.php', post_data, function(data) {
$('#notification').show();
});
});
</script>
and in your process.php:
<?php
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'subscribe' :
$email_address = $_POST['address'];
//do some db stuff...
//if you echo out something, it will be available in the data-argument of the
//ajax-post-callback-function and can be displayed on the html-site
break;
}
}
?>
It redirects to a different page because of your action attribute.
Try:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="text" name="address" id="email" maxlength="30" size="23" />
<input type="submit" value="" id="submit" name="submit" />
</form>
<?php if (isset($_POST['submit'])) : ?>
<p>Thank you for subscribing!</p>
<?php endif; ?>
The page will show your "Thank You" message after the user clicks your submit button.
Also, since I don't know the name of the page your code is on, I inserted a superglobal variable that will insert the the filename of the currently executing script, relative to the document root. So, this page will submit to itself.
You have to use AJAX. But that requires JavaScript to be active at the users Brwoser.
In my opinion it's the only way to do without redirect.
to send a form request without redirecting is impossible in php but there is a way you can work around it.
<form method="post" action="http://yoururl.com/recv.php" target="_self">
<input type="text" name="somedata" id="somedata" />
<input type="submit" name="submit" value="Submit!" />
</form>
then for the php page its sending to have it do something but DO NOT echo back a result, instead simply redirect using
header( 'Location: http://yourotherurl.com/formpage' );
if you want it to send back a success message simply do
$success = "true";
header( 'Location: http://yourotherurl.com/formpage?success='.$success);
and on the formpage add
$success = $_GET['success'];
if($success == "true"){ echo 'Your success message'; } else { echo
'Your failure message';
Return and print the contents of another page on the current page.
index.php
<html>
<body>
<p>index.php</p>
<form name="form1" method="post" action="">
Name: <input type="text" name="search">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_POST['search'];
include 'test.php';
}
?>
</body>
</html>
test.php
<?php
echo 'test.php <br/>';
echo 'data posted is: ' . $_POST['search'];
?>
Result:
Just an idea that might work for you assuming you have no control over the page you are posting to:
Create your own "proxy php target" for action and then reply with the message you want. The data that was posted to your php file can then be forwarded with http_post_data (Perform POST request with pre-encoded data). You might need to parse it a bit.
ENGLISH Version
It seems that no one has solved this problem without javascript or ajax
You can also do the following.
Save a php file with the functions and then send them to the index of your page
Example
INDEX.PHP
<div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>
Tools.php (It can be any name, note that it is kept in a folder lame tools)
<?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}
if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>
Use
form onsubmit="takeActions();return false;"
function takeAction(){
var value1 = document.getElementById('name').innerHTML;
// make an AJAX call and send all the values to it
// Once , you are done with AJAX, time to say Thanks :)
document.getElementById('reqDiv').innerHTML = "Thank You for subscribing";
}