Reputation: 2256
Is it possible to POST a form through jQuery and also handle the result? (without using json, ajax etc).
Something like this:
<form id="loginform">
//some input fields and a submit button.
</form>
and then from jQuery:
$("#loginform").submit(function (e) {
$.post("somePHPscript")
.done(function (response) {
//Handle response
});
});
.. or would that equal removing the form, and just binding an event to the submit-button, and take the inputs manually?
Upvotes: 1
Views: 806
Reputation: 2196
<form id="the-form" role="form">
<input type="button" id="button-form">
</form>
$("#button-form").on('click', function (e) {
e.preventDefault();
$.post($("#the-form").attr('action'), function(response) {console.log(response)});
});
Upvotes: 1
Reputation: 3332
The code you have will handle the response. You just have to do something with it. If you're returning a string of text, you can do something like this:
.done(function(response){
alert(response);
});
If you are returning some HTML, maybe something like this:
.done(function(response){
$(response).insertAfter('div');
});
EDIT
Of course, if you submit the form, then there is no point in trying to retrieve a response from the server. But right now your code is submitting the form and trying to do an AJAX request. Might as well stop the form from submitting and doing the AJAX request so you can do something with the response.
Upvotes: 1
Reputation: 1344
I'm not exactly sure why you would want a form that handles the submission result by overriding the default form action and not using ajax etc.
You will want to read this: http://api.jquery.com/submit/ which will outline how to capture the form submission event, you can prevent the move to another page by using the event.preventDefault()
as outlined in the above link.
Upvotes: 1