I want to send a URL in a POST request in a variable called surl. How should I encode it in JavaScript and decode it in PHP? For example, the value of surl could be http://www.google.co.in/search?q=javascript+urlencode+w3schools.
EDIT
Sorry, I forgot to mention, it's not form submission but a ajax request.
You don't need to to anything. Send it as is. Browser and PHP will do all escaping and unescaping for you (if you use form.surl.value = surl; form.submit() and $_POST['surl']). Or you can just use the plain form without any JavaScript (if it fulfills your needs).
Replying henasraf's comment. Try this.
<form id="form" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post"
onsubmit="this.via_js.value=this.via_plain_form.value;">
<input type="hidden" name="via_js"/>
<input type="text" name="via_plain_form" value="Paste you url here"/>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
if (isset($_POST['submit'])) {
var_export($_POST);
}
?>
For http://www.google.co.in/search?q=javascript+urlencode+w3schools, it outputs
array (
'via_js' => 'http://www.google.co.in/search?q=javascript+urlencode+w3schools',
'via_plain_form' => 'http://www.google.co.in/search?q=javascript+urlencode+w3schools',
'submit' => 'Submit',
)
Use encodeURIComponent(uri) (for encoding) and decodeURIComponent(uri) for decoding,
E.g (encoding).
var uri="http://w3schools.com/my test.asp?name=ståle&car=saab";
document.write(encodeURIComponent(uri));
Output
http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
Decoding is left for the reader. :-)
Source: http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp
As for PHP, it's urlencode() and urldecode().
Related
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.
I'm trying to add a value to $_POST data while it gets submitted to the target page as follows:
post.php
<?php $_POST['field1'] = "Value1";?>
<html>
<head>
</head>
<body>
<form method="post" action="catch.php">
<input name="field2" type="text"/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
catch.php
<?php
foreach ($_POST as $key => $value) {
echo $key . " : ". $value;
echo "<br/>";
}
?>
but I cannot catch 'field1' on the other end. I don't want to use a hidden input field. How can I achieve that?
Thanks!
When you send the form, the $_POST data is reset and assumes only the inputs inside the form and a possible query string you may have appended to form action.
The best way to accomplish what you want is using hidden field but since you dont want it, you can append a query string to your form action:
<form method="post" action="catch.php?field1=Value1">
You're not submitting field1 anywhere. What happens is this:
post.php generates a HTML page (one that doesn't contain any reference to field1)
the user's browser renders the page
on submit, only the elements inside the form are submitted
catch.php receives the elements submitted above.
In other words, you need to get that value into your form:
<form method="post" action="catch.php">
<input name="field2" type="text"/>
<input name="field1" type="hidden" value="<?php echo htmlspecialchars($_POST['field1']) ?>"/>
<input type="submit" value="Submit" />
</form>
There is no other way to get the value into your POST data, if it's not present in the form. What you could do as a workaround is store the data in GET (size limit), session (concurrency issues - what happens when the user has two tabs open, each with different session data?), or cookies (size limit AND concurrency issues).
You can't do it this way. If you want to send the data you're trying to add to the POST there only through the users form, you are forced to also store it somewhere client side (e.g. a hidden field or a cookie). What you're doing right now is setting some value into the POST variable, but it gets overridden by the users form post (or rather the $_POST variable you're using after the form post is another instance).
What you could do instead to keep it serverside is save the value in the variable to the session of the user, then in the form post action server side get the value again (given the fact that you're using sessions). Lastly you could just store it in some table in a database, though I wouldn't do this.
Since $_POST are data sent by post method to script, you can not use it for another request directly. You need to compose and send another post request. The easiest way for you will be to use hidden input field/s.
Or you can choose another approach to make http post request, for example curl methods.
If you don't need data to be given by post method, you can save it in session, for example.
try this:
in post.php
<?php $_SESSION['field1'] = "Value1";?>
<html>
<head>
</head>
<body>
<form method="post" action="catch.php">
<input name="field2" type="text"/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
in catch.php
<?php
if(isset($_SESSION['field1']))
{
$_POST['field1'] = $_SESSION['field1'];
unset($_SESSION['field1']);
}
foreach ($_POST as $key => $value) {
echo $key . " : ". $value;
echo "<br/>";
}
?>
Make sure you have started the session.
Note: you must use hidden elements or query string as other user suggested.
I have string parameter with apostrophes that I need to pass it to another php page.
My code is:
echo '<form name="submitForm2" action="creatDocument.php?$formulation='.$formulation.'" method="POST">
<input type="submit" value="pass"/>
</form>';
The $fomulation parameter contain the string with hebrew characters that came from user.
if $fomulation = אבג"דה
creatDocument.php received just $fomulation = אבג .
How can I fix it?
What's happening is that the URL parser is breaking on the single quotes. Check out the URLEncode method, to encode your query string parameters.
http://us3.php.net/urlencode
echo '<form name="submitForm2" action="creatDocument.php?$formulation='.urlencode(utf8_encode($formulation)).'" method="POST">
<input type="submit" value="pass"/>
</form>';
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).
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.