In my application I'm using a plugin that generates the following markup:
<form id="addCommentForm"
action="/foo/add"
method="post"
onsubmit="
jQuery.ajax({type:'POST', data:jQuery(this).serialize(),
url:'/foo/add',
success:function(data,textStatus) {
jQuery('#comments').html(data);
},
});
return false">
<!-- form elements here -->
</form>
When the form is submitted successfully I want to do something else after the success handler defined by the plugin, say alert('hello');.
The reason I'm struggling with this is because I can't just add my code to the end of the success handler above, because this code is not under my control.
I looked for a form event that executes after onsubmit that I could attach my code to, but didn't find anything.
If you can't really change it, you could use .ajaxSuccess() to handle all the external ajax calls and filter the one you need:
$('form').ajaxSuccess(function(evt, request, settings) {
if (settings.url == 'xxx')
alert('test');
});
Not pretty but it might work for you.
Related
I have a page which calls an external library, this library adds a payment form:
<form name="multipay_form" onsubmit="private_payment_send(); return false;">
....
</form>
I can not change any code here. I need to call a function after form is submitted. What I have done is:
jQuery('form[name="multipay_form"]').on('submit', function() {
alert("myfunction");
});
Which works ok, but there is one exception, the method "private_payment_send()", does form validation, I need to know if their function returned true or false, to be able to trigger my function or not.
Is this possible?. I want to avoid doing the validation again on my end, since if they add new field or any new rule I would have to do the same on my code, which is not optimal. Any ideas?
Is there a way to unattach the function from the form through javascript?, in that way I can call private_payment_send() from my function
<form name="multipay_form" onsubmit="private_payment_send(); return false;">
<button type="submit">test</button>
</form>
document.getElementsByName("multipay_form")[0].setAttribute('onsubmit','');
This will make it so the onsubmit is removed from the form without touching the HTML
Try to use done() function in Jquery
.done(function( n ) {
$( "p" ).append( n + " we're done." );
});
Following is Jquery documentation
https://api.jquery.com/deferred.done/
You can trigger your function only when the called function, here "private_payment_send" has returned true. This can be done like this
<form name="multipay_form" onsubmit="if (private_payment_send()) { alert("myFunction") }; return false;">
...
</form>
If you only want to use the jQuery part, you can completely remove the onSubmit attribute and only assign the submit handler using jQuery
jQuery('form[name="multipay_form"]').on('submit', function() {
if (private_payment_send())
alert("myfunction");
return false;
});
Well, I spent hours on this problem and scanned the whole stackoverflow, but still do not know what to do. But what really gets me nuts is that such a trivial and the simplest in the world thing is not working. So, what I have now is a form with inputs and a button:
<form id="frm" action="/accent/login/enter/">
{% csrf_token %}
<div draggable="true" id="panel" class="panel" title="">
<input id="login" name="login" type="text" placeholder="" class="required" /> <br/>
<input id="pswd" name="pswd" type="password" placeholder="" class="required" /> <br/>
<button id="btn" value="">ENTER</button>
</div>
</form>
And I have this code which is supposed to send the form:
$('#btn').one("click",function(){ // prevent from multiple submits
$('#frm').validate({ // validate the form before submission
...general stuff: rules, messages, etc
submitHandler:function(form){
$('#frm').submit(function(e){ //submitted on the second click. why???
...prepare parameters for ajax call
$.ajax({
type:'POST',
...general stuff
});
e.preventDefault();
})
}
});
});
The problem is, when a user clicks on submit button for the first time, then the form is not submitted, if, however, he or she clicks it for the second time, then it is submitted ok. I can't understand the logic behind such behaviour implemented in jquery. Besides, I should say, that I have tried many other tricks, like:
form.submit(...
$('#frm')[0].submit(...
But they work not as expected, as if there is no callback function - I'm redirected to the url, but do not stay on the same page - just what I expect from e.preventDefault. I guess there is some sacred method or magic properties in jquery that I should use to make it work (like method one which prevents terrible multiple submits). But at this moment I do not know them.
EDIT
I also tried this trick:
jQuery('#frm').submit(...
but it works exactly like the first method - $('#frm').submit(...
EDIT
I found the third method which works like the previous one:
$('form').submit(...
To sum up, I have three different methods, but all of them work only when a user clicks on the button for the second time. And I have two methods that work in a standard manner and do not make it possible to use a callback function.
The problem is, you are registering for form submit after the form validation.
so,
1) On first click of button validation, the submit event is registered to a handler.
2) On second click of the button, the registered handler will be called. that is why it get submitted on second click. But note that you are registering again for the submit event. which means, on third click the form will be submitted twice, on fourth click the form will be submitted thrice..... and so on...
Solution
1) remove the $("#frm").submit() code from the submitHandler and put it outside.
2) use e.preventDefault(); in $("#frm").submit() so the default action is prevented and page doesn't get reloaded.
3) put the AJAX code directly in submitHandler
$('#btn').one("click",function(){ // prevent from multiple submits
$('#frm').validate({ // validate the form before submission
...general stuff: rules, messages, etc
submitHandler:function(form){
...prepare parameters for ajax call
$.ajax({
type:'POST',
...general stuff
});
}
});
});
$('#frm').submit(function (e) {
e.preventDefault();
});
I guess you are using the jqueryvalidation plugin. If it's true, then your using of $().validate() may be wrong.
The $().validate() function is to initialize the validation, it tells the script how to validate the form value and what to do if the validation is passed(the submitHandler property).
So maybe you should edit your code like this:
<form id='frm'>
...
</form>
$('#frm').validate({
//...general stuff: rules, messages, etc
submitHandler: function (form) {
//blahblah before doing the submitting...
form.submit();
}
});
$('#btn').one('click', function (){
$('#frm').submit();
});
But, actually there's still a problem with your $btn.one() event handler: if you click the button while the form values doesn't meet your validation rules, the one chance to fire the handler is consumed and even if you re-input the right value, the button will never response your clicking unless refreshing the page.
So maybe you should check your business logic again and redesign the form submitting flow, but that's not what this question is discussing, good luck ;)
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?
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.
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.
<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)});
});
I have a form on my site where users submit stuff and get results
<form accept-charset="UTF-8" action="/submit-stuff" data-remote="true" method="post">
<!-- various form fields -->
<input type="submit" value="Run Code" id="submit-button">
</form>
Before submitting their info to the backend, I try to get the results in Javascript. If I can get the results, I return false in Javascript to prevent the form submission.
$('#submit-button').click(function() {
if(canGetResults()){
//deal with submission and then
return false;
}
//the button will work as usual if canGetResults is false or there's an error
});
This works fine, but now I want to try to get the results through another ajax request and only submit to my regular backend if that fails. I call the following code after the button is clicked:
$.post("http://example.com/submit-stuff", json, function(data) {
//do stuff with data
});
However, it's asynchronous (so I can't return results from it) so the code reaches return false even when the other ajax attempt fails. How should I fix this so it only submits to my own backend when the ajax attempt failed?
I could change the $.post to $.ajax and make it synchronous, but that's not usually recommended. Alternatively, I can submit the form within the $.post callback, but how should I submit the whole form from there? And would it still submit if there's an error or http://example.com/submit-stuff doesn't work?
Your submit handler should always prevent the form from submitting.
Then, if the Ajax code comes back with an OK, you should call the form's submit() method. This will bypass the submit handler and submit the form.
NB: Call submit on the DOM object, not the jQuery object. jQuery has a habit of triggering event handlers from its wrappers.
You can bind the ajax request all in your submit function, and call a .post() event if necessary:
$("form").submit(function(e){
e.preventDefault(); // <-prevents normal submit behaviour
//only post if your ajax request goes your way
$.ajax(url,function(data){
//argument to post or not
if(data=="success"){ postForm(); }
});
});
function postForm(){
$.post(
"/submit-stuff"
,$( "form" ).serialize()
,function(data){
//your code after the post
});
}
If you do not want to create a separate function for your postForm, then you can just put it inside the wrapper where it's currently being called.
There are a few similar questions to this but none quite the same.
I want to know if there is an event that can be used to execute some JS before a page is submitting (i.e. POSTed).
Something like this?
<form onsubmit="do_something()">
function do_something(){
// Do your stuff here
}
If you put return like the code below, you can prevent the form submission by returning false from the do_something() function.
<form onsubmit="return do_something()">
function do_something(){
// Do your stuff here
return true; // submit the form
return false; // don't submit the form
}
If you are working with the form, you can use onsubmit event.
Using jQuery you can do that with
$('#myform').submit(function() {
// your code here
});
You can bind an event handler to the submit event (following code assumes you have an id on your form):
document.getElementById("someForm").onsubmit = function() {
//Do stuff
};
Yes, you can use on the onsubmit event on your form.
In pure HTML (without jQuery), you can use:
<form onSubmit="mySubmitFunction()">
...
</form>
More details here: https://www.w3schools.com/jsref/event_onsubmit.asp
The following code will abort the submission from the window level, which will not submit the form.
window.onsubmit = function() { alert('aborting submit'); return false; };
Tested with IE11, so it should work for some legacy applications without jQuery.