Acidic Cloud
Acidic Cloud

Reputation: 607

How do I submit my form using href?

Am using this onclick='document.forms['form_name'].submit(); return false;' but this doesn't work as am having href=results.php?page_no=1 etc, has dynamic links, examples show to make this work I need to use href="#" but any idea how I can submit the form and than navigate to page2? Because I want to save the check box values in a session

Upvotes: 0

Views: 9160

Answers (4)

Tom
Tom

Reputation: 642

Add class to your hrefs (class="pagination") and id (id="form") to your form. Then you can use Jquery framework for this stuff.

$(".pagination").click(function(){  
// get page id, set form action with params
$("#formId").submit();

return false;  
});

Upvotes: 2

Jesse Baynard
Jesse Baynard

Reputation: 16

Some options:

1) Use jQuery AJAX, serialize and post the form data and then redirect (location.href) on the onSuccess callback. Something like this:

$.post("submitform.php", 
       $("form").serialize(),  
       function(data){location.href='results.php?page_no=2';}
      );

2) Post the form to a named hidden iFrame using "target" on the form tag. If this is really just a best effort sort of recording you shouldn't need to wait for the page to load, the request should be enough and you can continue to the next page. Something like this:

<iframe="targetname" style="display:none;" />
<form name="myform" target="targetname" method="post" action="submitform.php">
....
</form>
<a href="page2.php" onClick="document.forms['myform'].submit(); return true;">
Click Here
</a>

Upvotes: 0

user1646111
user1646111

Reputation:

Here I substituted page2 with Google just for test

<a href="#" onclick="document.forms['test'].submit(); return false;">Submit</a>
<form method="get" action="https://www.google.com/search?q=test" name="test">
<input name="Checkbox1" type="checkbox" />
</form>

edit:

<a href="page2.php?page=2" onclick="document.test.action =encodeURIComponent(this.getAttribute('href')); document.forms['test'].submit(); return false;">Submit</a>
<form method="get" action="" name="test">
<input name="Checkbox1" type="checkbox" />
</form>

without encodeURIComponent(this.getAttribute('href') the parameters are missed.

Upvotes: 0

Jordan
Jordan

Reputation: 32522

You have a bad design.

You can't perform multiple competing actions on a form click and expect it to work.

You need to either let the link be clicked and let it load another page, or if you are just setting some session variable (although it would be far better to set this with a querystring parameter or a cookie), you can use an Ajax request to send that off asynchronously.

Upvotes: 0

Related Questions