Link to home
Start Free TrialLog in
Avatar of bswinnerton
bswinnertonFlag for United States of America

asked on

Pass hidden form using javascript onclick

I'm looking for a way to pass the contents of a hidden form to the next page using a javascript onclick function.

What I have right now is(this is in php):
$postid = $row['id'];
echo "<form name=\"id\" method=\"post\"><input type=\"hidden\" name=\"id\"></form>";
echo"<a href=\"/blog\" onclick\"javascript: document.form.id.value='$postid'; document.form.action=\"/posts/index.php\"; document.form.submit();\"\">$title</a>";

And then on posts.php I have:
$id = $_POST['id'];

But for some reason it isn't returning anything. Can someone shed some light on the situation? I'm quite the novice with javascript.
Avatar of theremon
theremon
Flag of Greece image

Hi there

first of all the escaping of your second echo statement is wrong. Check the code below:

echo"<a href=\"/blog\" onclick=\"document.form.id.value='$postid'; document.form.action='/posts/index.php'; document.form.submit();\">$title</a>";

Open in new window

One other thing that you should have in mind, is that you'll never actually see the output of posts/index.php.
It might not even be executed properly (but that depends on a variety of reasons)
Right after your javascript code is executed, the page should refresh as is the normal browser behaviour. Instead, you're kind of making two calls at once. One "normal" post and at the same time a normal link. You really don't have any assurances that this will work properly.
I believe it would be a lot safer to throw in a bit of ajax in there to handle your form post and then redirect to the page you want.
SOLUTION
Avatar of rjdown
rjdown
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial