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.
LVL 5
bswinnertonAsked:
Who is Participating?
 
theremonConnect With a Mentor Commented:
What you're saying is totally correct. I took for granted the asker is aware of this.

I also just noticed another problem. Both the form and the field are named "id". That can only produce problems. Also, document.form works best in IE, but not that good in all other browsers.
Please change that to something like the code below.
Even though it will still not work. The link to /blog will fire so fast, that the form won't get properly posted.
echo "<form name=\"fid\" method=\"post\"><input type=\"hidden\" name=\"fldid\"></form>";
echo"<a href=\"/blog\" onclick=\"document.forms[0].fldid.value='$postid'; document.forms[0].action='/posts/index.php'; document.forms[0].submit();\">>$title</a>";

Open in new window

0
 
theremonCommented:
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

0
 
theremonCommented:
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.
0
 
rjdownConnect With a Mentor Commented:
Bear in mind that even using AJAX, your code will fail if JavaScript is disabled.

Is there any reason why you can't add the extra hidden data to the original form using <input type="hidden"....> ?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.