1

I am trying to use jquery to submit a form, but instead of the default action script that is in the form, I would like to submit the post variables to different action script instead.

More specifically, this is my default form that works a particular way when a user clicks the submit button:

<form method="post" action="something.php" id="myForm"> 
</form>

What I am trying to do is submit the form above, but instead of using the default something.php as the action script I would like to use the foo.php.

Is this even possible? This is what I tried, with no success (the post vars arent getting passed to the foo.php page):

$.post('foo.php', '#myForm', function(data) {
    alert(data);
}); 

I appreciate any suggestions on how to do this.

Many thanks in advance!

2 Answers 2

2

If you simply want to change where the form posts to, then change the action attribute with JavaScript.

$('#myForm').attr('action', 'foo.php');

Only use $.post() if you intend to change the default behaviour to use an XHR instead of a normal whole-page refresh.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply. Well, I want to temporarily change the action attribute. I would like to default action script to remain...
@MiGusta Then you could store the original value, and replace it when you need to.
+1, thank you, I like your method a lot, however, I ended up using the other one because It requires less code modification. Your way is a simpler solution however :D
1

Yes, this is possible of course, but you should pass a key-value pair, you can use .serializeArray() method.

$('#myForm').submit(function(e){
   e.preventDefault();
   $.post('foo.php', $(this).serializeArray(), function(data) {
       // alert(data);
   }); 
});

If you have a click handler:

$('#element').click(function(e){
   //e.preventDefault();
   $.post('foo.php', $('#myForm').serializeArray(), function(data) {
       // alert(data);
   }); 
});

2 Comments

Thanks for the reply. How can I trigger this submit function? I am trying to manually trigger it... Because what I did is I placed the provided code in a click event so when a user clicks on some particular button, the code above gets executed, but the code above seems like an event listener, so I would need to trigger it manually...
@MiGusta If you have a click handler you don't need to listen to submit event, I have updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.