Change Response URL without Redirect - php

Is it possible to change the response URL without performing a redirect?
The slightly longer story...
Due to a limitation with HTML forms the following does not work because the query string from the action URL is not submitted to the server:
<?php // handler.php ?>
...
<form action="handler.php?lost=value" method="get">
<input type="text" name="filter-keyword" value="" />
<input type="submit" name="do-submit" value="Submit" />
</form>
...
So I decided to switch to using the post method and create a separate filter handler script which simply constructs the correct query string for the "handler.php" file.
<?php // handler.php ?>
...
<form action="filter-handler.php" method="post">
<input type="hidden" name="preserve-qs" value="lost=value" />
<input type="text" name="filter-keyword" value="" />
<input type="submit" name="do-submit" value="Submit" />
</form>
...
// filter-handler.php
<?php
$new_url = 'handler.php?filter-keyword=' . $_POST['filter-keyword'];
if (isset($_POST['preserve-qs']) && $_POST['preserve-qs'] != '')
$new_url .= '&' . $_POST['preserve-qs'];
header("Location: $new_url");
?>
Is it possible to achieve this without performing a redirect?
// filter-handler.php
<?php
$qs_args = array(
'filter-keyword' => $_POST['filter-keyword'];
);
if (isset($_POST['preserve-qs']) && $_POST['preserve-qs'] != '')
parse_str($_POST['preserve-qs'], $qs_args);
// Fake query string.
$_GET = $qs_args;
// handler script is blissfully unaware of the above hack.
include('handler.php');
// ???? HOW TO UPDATE QUERY STRING IN BROWSER ADDRESS BAR ????
// Following no good because it redirects...
//header("Location: $new_url");
?>

Yes and no.
No, because to actually really change the URL from the server side you have to make a redirect.
Yes, because there are other solutions to your problem.
Solution no. 1:
Change your code from the first example into:
<?php // handler.php ?>
...
<form action="handler.php" method="get">
<input type="hidden" name="lost" value="value" />
<input type="text" name="filter-keyword" value="" />
<input type="submit" name="do-submit" value="Submit" />
</form>
...
and this should result in proper URL (with lost=value).
Solution no. 2 (ugly one):
Overwrite $_GET array at the beginning of the script to cheat the application into believing the GET parameters were passed.
Solution no. 3 (about changing URL without redirect):
This solution is probably not for you, but it actually imitates changing URL. It is not on the server side, but it actually changes the URL for the user. This is called pushState (demo here) and this is HTML5 / JavaScript feature.
If you can use JavaScript and make AJAX requests, this solution may be perfect for you (you can eg. call whatever URL you like and dynamically pass data you need, even altering the values of the form fields you would submit).

Related

How to add input value to URL in php

I have a question from php and I'm not expert in php.
1.I have html page with one form include a text box and submit button .
2.I have a static target url like this : https://example.com/invoice/XXXXXXXXXXXXXX
XXXXXXXXXXXXXX is just numbers and has 14 characters.
*** What I need is that my customer enter its 14 characters number in input text form and when it submit , goes to target url.I want to check input form for entry numbers too.
I make a sample form like this but not work:
<form action="https://example.com/invoice" class="pey-form" method="get">
<input type="text" id="peyid" name="peyid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="14" ><br><br>
<input type="submit" value="submit">
</form>
What can I do?
As hassan said , you can do this only with javascript.
This will redirect to the url what you desired.
document.querySelector("form").onsubmit = function(){
this.setAttribute("action",this.getAttribute("action")+"/"+document.querySelector("[name=peyid]").value);
}
For example
If document.querySelector("[name=peyid]").value = 12345678901234 The url will look like https://example.com/invoice/12345678901234?peyid=12345678901234
So if you just need to redirect to that url you don't even need form just
<input type="text" id="peyid" name="peyid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="14" ><br><br>
<input type="button" value="submit">
<script>
document.querySelector("[type=button]").onclick = function(){
location.href = `https://example.com/invoice/${document.querySelector("[name=peyid]").value}`;
}
</script>
Using PHP—to receive a form value, validate it, apply it to a URL, and redirect the client to that location, use $_POST, preg_match(), string interpolation, and header().
/invoice/index.php:
<?php
if ( isset($_POST['peyid']) && preg_match("/^\d{14}$/", $_POST['peyid']) ) {
header("Location: http://www.example.com/invoice/{$_POST['peyid']}");
exit;
}
?>
<html><head><title>oops</title></head><body>An error occurred.</body></html>

use $_GET['']; value inside $_POST[''] and submit it to the same page and display in the same page

i am new to php and while i am practing i came across a problem. actually,i have two files index1.php and index2.php. in index1.php i have a link with a unique id as
<a href="index2.php?companyid=<?php echo $row('company_id');?>>details</a>
i have got this value in index2.php as
if(isset($_GET['companyid'])){
$companyid = $_GET['companyid'];
}
now i have a search form in the index2.php as
<form method="POST" action="index2.php">
<input type="text" name="search">
<button type="submit" name="submit">submit</button>
</form>
now on button click i want the search results be displayed in the same page as
'index2.php?companyid=$companyid'
but some how if i try to use $_POST['submit']; in the same page it takes me to index2.php and instead of index2.php?companyid=$companyid and also it throws error as undefined index of $companyid if i don't use $_POST['submit']; and echo $companyid; it gives value and works fine. all i want is that to use $companyid' value inside ``$_POST['submit']; as and display the result in the same url as before
if(isset($_POST['submit']){
$companyid //throws an error index of company id
}
any help will be appreciated
First off, it looks like you are not using the company id in the form itself, so it will not be submitted as part of the the POST. You could possibly use:
<form method="POST" action="index2.php">
<?php if (isset($companyid)): ?>
<input type="hidden" name="companyid" value="<?= $companyid; ?>">
<?php endif; ?>
<input type="text" name="search">
<button type="submit" name="submit">submit</button>
</form>
But you would probably also need to change your logic to:
if(isset($_POST['companyid'])){
$companyid = $_POST['companyid'];
}else if(isset($_GET['companyid'])){
$companyid = $_GET['companyid'];
}
As Josh pointed out in the comments, PHP is not able to remember your previous GET request but this can easily be solved by altering the action attribute of the form element. By doing this you can pass on the previous data. This would look a little something like this:
<form method="POST" action="index2.php?companyid=<?php echo $companyid;?>">
<input type="text" name="search">
<button type="submit" name="submit">submit</button>
</form>
This way you will be redirected to index2.php with the URL parameters present and you will be able to retrieve both search and companyid using $_POST and $_GET or use $_REQUEST for both.

Send form data to the same page not functionning

I'm a newbie in PHP, and I would like to send datas from a form and display it into the same page, here is my code for better understanding:
<form method="post" action="same_page.php">
<input type="text" name="owner" />
<input type="submit" value="Validate" />
</form>
<?php
if(isset($_GET['owner']))
{
echo "data sent !";
}
?>
So normally, after having entered some random text in the form and click "validate", the message "data sent!" Should be displayed on the page. I guess I missed something, but I can't figure out what.
You forgot to add submit name in your form.You are using POST as method so code should be
<form method="post" action="">
<input type="text" name="owner" />
<input type="submit" name="submit_value" value="Validate" />
</form>
<?php
if(isset($_POST['submit_value']))
{
echo '<pre>';
print_r($_POST);
}
?>
Will display your post values
You are using a POST method in your form.
<form method="post" action="same_page.php">
So, change your code to:
if (count($_POST) && isset($_POST['owner']))
Technically, the above code does the following:
First checks if there are content in POST.
Then, it checks if the owner is set.
If both the conditions are satisfied, it displays the message.
You can actually get rid of action="same_page.php" as if you omit it, you will post to the same page.
Note: This is a worst method of programming, which you need to change.
You should Replace $_GET['owner'] with $_POST['owner'] as in your form you have specified method='post'
Replace:
$_GET['owner']
With:
$_POST['owner']
Since you are using the post method in your form, you have to check against the $_POST array in your PHP code.

Set Call to PHP Function, with POST Variables as Parameters, as HTML Form Action

I currently have an HTML file, with a form in it, that when submitted POSTs the form & calls a simple short PHP file that calls a function within another PHP file using the POSTed variables as parameters. The files are both below. What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
Ideally, this would set the call to the function:
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
as the form action. Does anyone know how/if this can be achieved?
HTML:
<FORM ID="FORM1" METHOD="POST" AUTOCOMPLETE="off" ACTION = "writeToDL.php">
<INPUT TYPE="hidden" NAME="Date" STYLE="WIDTH:0px; " MAXLENGTH="8" TITLE="Enter Date" Value="<?php $dt = date('Y-m-d'); echo $dt ?>"/>
<INPUT TYPE="text" NAME="Time" STYLE="WIDTH:70px; " MAXLENGTH="7" ONCHANGE="validateTime();" />
<SELECT NAME = "Result">
<OPTION VALUE = OK></OPTION>
<OPTION VALUE = C>C</OPTION>
</SELECT>
<SELECT NAME = "Participant" STYLE = "WIDTH: 187">
<OPTION SELECTED VALUE = "">Select...</OPTION>
<?PHP
$allParticipants = getall_participants();
foreach($allParticipants as &$value) {
$val = $value->get_id();
echo "<OPTION VALUE='",$val,"'>";
echo $value->get_first_name()," ",$value->get_last_name();
echo "</OPTION>";
}
?>
</SELECT>
<TEXTAREA NAME='Notes' COLS='28' ROWS='5'></TEXTAREA>
<INPUT TYPE="image" SRC = "images/submit.png" VALUE="Submit Participant"/>
</FORM>
PHP File:
<?php
include_once('database/PE.php');
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
?>
You COULD do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include_once('database/PE.php');
insert_PE(new PE($_POST['Date'],$_POST['Participant'],$_POST['Time'],$_POST['Result'],$_POST['Notes']));
} ?>
<html>
... rest of your page here ...
</html>
That way the PHP code only fires if an POST was actually performed. Some would suggest checking for the presence of a form field, but that's unreliable - you might change the form down the road and forget to update the if(). Checking the request method is guaranteed to be 100% reliable.
What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
No. The client only knows about URIs.
A URI can map to a PHP program. Multiple URIs can map to the same PHP program. You can use logic to determine what functions to run for a given URI. You can't avoid having that logic in your program.
One option is to put method="_the_main_php_file_containing_function_to_be_called_"
I hope it works fine.
I think you could use a hidden field on the form, and populate it with the name of the function you want to run on "destination.php". Then a switch statement on "destination.php" could pull the name of the function from POST variable.

jQuery + hidden input fields

A simplified version of problem I am experiencing:
Here is my HTML form:
<form enctype="multipart/form-data" method="post" action="/controller/action">
<input type="text" name="title" id="title" value="" class="input-text" />
<input type="hidden" name="hidden_field" value="" id="hidden_field" />
<input type="submit" name="submit_form" id="submit_form" value="Save" class="input-submit" />
</form>
Here is the JavaScript:
$(document).ready(function() {
$('#submit_form').hover(function() {
$('#hidden_field').attr('value') = 'abcd';
});
});
And here is a really short version of the PHP backend:
if (isset($_POST)) {
var_dump($_POST);
}
What I do is I hover the #submit_form button for a few seconds just to make sure that the jQuery code got executed, then I submit the form and:
the $_POST['hidden_field'] is empty!
Why is that? It should contain 'abcd' as I insert it into the hidden field with jQuery on the hover event.
Correct way to set the value:
$('#hidden_field').val('abcd');
Reference: http://docs.jquery.com/Attributes/val
The statement
$('#hidden_field').attr('value') = 'abcd';
is incorrect. You should get an error there as you're assigning an rvalue (the jQuery object) to another rvalue (a string). (The assignment operator needs an lvalue (e.g. a variable) on the left.)
You probably want:
$('#hidden_field').val('abcd');
or:
$('#hidden_field').attr('value', 'abcd');
(The former is more jQuery-ish, but for this case both are equivilent.)
it is:
$('#hidden_field').attr('value','abcd');
Since these are hidden elements be sure to check these with something other that viewing the page source i.e. pressing F12, check with alert(), etc. The source of the original html page will not reflect changes made to it via javascript.

Categories