click and mousedown events don't work on Ajax form - javascript

Simple Ajax popup with a form collecting 3 fields of data, and a submit button. I can't programatically trigger the submit button though.
jQuery('#FormSubmit').click()
doesn't work. Neither does
jQuery('#FormSubmit').mousedown()
nor
document.getElementById("FormSubmit").click();
A real mouse click on the button works, but programmatically triggering it doesn't. It either posts the form in a non-AJAX way (page reload with post data appended to the url) or does nothing.
Anyone know the reasons why?
Is there something specific to Ajax to prevent this?
Edit:
Just tested triggering the submit event on the form instead, and that also posts the form in a non-AJAX way.

You need to use submit, or if you want you can write something like this:
`$('#formSubmit').on('click', function (event) {
event.preventDefault();
var input1 = $('#someInput1').val().trim();
var input2 = $('#someInput2').val().trim();
$.ajax({
url: 'someUrl',
type: 'POST',
success: function (result) {
//do something with the result
}
})
})`

try to use trigger, like this
jQuery('#FormSubmit').trigger("click");

Related

How to set Autoclick on all the buttons of a page?

I am using Jquery and Ajax for performing the action, I need after loading complete page, a code click on the every button automatically.
I used the following javascript code for click all the buttons in the end of my page. but it is not working.
<script type='text/javascript'>
document.getElementByClassName('sub').click();
</script>
Structure of my Page code
[JQuery]
[PHP]
[HTML]
[Javascript]
I set all the buttons type as "BUTTON", When I set
type="submit"
The Autoclick code only work on the first button, but with the "button" type it is not working with any of them.
If I click manually on that buttons they are working properly.
Please give any suggestion. Thank You.
Youre using the wrong function. Elements is plural in that method.
document.getElementsByClassName('sub');
Additionally, calling click on this NodeList will not work. You need to loop through and call the event on each index.
Also, you say you're using jQuery. To ensure your call happens after DOM ready, wrap your JS with $().ready().
Last, use the tools you've provided yourself, in this case jQuery, and select your element that way.
$(document).ready(function(){
$(".sub").click()
});
In jQuery you can trigger the click like
$( ".sub" ).trigger( "click" );
Because you retrieve a NodeList(as pointed out in the comments) :
$(document).ready(function () {
var butEl = document.getElementsByClassName('sub'),
count = butEl.length;
for (i = 0; i < count; i++){
butEl[i].click();
}
});
Also is getElementsByClassName
If you're trying to click on multiple different form submit buttons, it makes sense that the browser will POST for only one of them - one page can't simultaneously navigate to multiple different URLs.
Similarly, when you change type to button, none of the forms will be submitted, even though you're clicking on the buttons.
If you know what you're doing, you could always add submit event handlers to all of your forms, and submit them via ajax requests instead - which should allow multiple of them to be processed. Note you may need to work out some extra logic for displaying success/failure for each form to the user since the browser won't navigate you to any of the existing "submitted" pages.
$(document).on('submit', 'form', function() {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
// Add logic here for handling success for each form, if required
},
error: function(xhr, err) {
// Add logic here for handling errors for each form, if required
}
});
return false; // To stop the browser processing this form
});
With this method, your first attempt with type="submit" buttons should work - however I would encourage you to be as specific as possible with your element selectors for both the forms and the buttons you're trying to target.

jQuery and Django form validation re-load and submit event listener

I'm trying to save/validate a django form via an AJAX POST request.
Everything works just fine when the submit button is hit the first time, but, if the server-side validation fails and the form needs to be loaded again for the user to update the inserted contents, the event listener is not catching any further submit event and the default behavior applies.
This is the related code I have under $(document).ready(function()
$(document).on('submit', '#myForm', function(event)
{
event.preventDefault();
$.ajax({
url: 'ajax/saveForm/',
data: $('#myForm').serialize(),
type: 'POST'
}).done(function(data) {
$('#myForm').html(data);
});
});
In other words : once the html code of the form has been replaced using the $('#myForm').html(data); instruction the $(document).on('submit'... is not anymore going to be called on submit events despite jquery's on event listener is supposed to work with future elements matching the selector.
EDIT:
Binding the click event on the form submit button works.
$(document).on('click', '#myFormSubmit', function(event)
{
event.preventDefault();
$.ajax({
url: 'ajax/saveForm/',
data: $('#myForm').serialize(),
type: 'POST'
}).done(function(data) {
$('#myForm').html(data);
});
});
Any idea why ?
I can't say for sure what is wrong, but I have a feeling it has to do with the done method (because maybe after the a failed run, it doesn't know what to do). You might need to explicitly tell it what to do in case of failure:
$('#myForm').on('submit', function(e) {
e.preventDefault();
var form = $(this);
$.post({
url: 'ajax/saveForm/',
data: form.serialize(),
success: function(response) {
alert('yey!');
},
error: function(response) {
form.html(data);
}
});
});
I also avoided $() the entire document, used $.post and cashed the form object into a variable, but those shouldn't have any actual effect (they're just conventions). Tell me if this works or not, I'll try and help. Also, try using chrome developer tools (i.e console.log(whatever)), it's really great for debugging

How do you send an ajax request every time that a form input field changes?

For example, there is an input field. Every time a user types a key into that field, it sends an AJAX request with whatever text is currently in that input, and does something with it. I've looked into the change and keyup functions in Jquery, but when I try them in Jsfiddle they don't do anything. Is there a standard way of doing this type of operation? I know its common for validations and stuff.
<form>
<input id="test" type='text' >
<input type="submit" value="asdf">
</form>
$('input').on("change",(function(e){
alert("Hello");
});
The effect I am going for is like this game www.sporcle.com/games/g/nflteams#
You can type in any text and if its within the set of correct answers then the table will update to show that answer. You never have to submit. How do you suppose they achieved this effect?
It seemed to me like they must be querying the database every time a user enters a key, to see if it is a correct answer. If it is they update the table to display the answer. What are other ways to do this?
sending a request on each change is just bad, delay the ajax on the last change
var changeTimer = false;
$("your inputs").on("your change event",function(){
if(changeTimer !== false) clearTimeout(changeTimer);
changeTimer = setTimeout(function(){
/* your ajax here */
changeTimer = false;
},300);
});
I'd probably do something similar to this.
you'd have to add some extra code to handle dropdowns, but the idea is the same.
$('form input').keyup(function () {
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
Just make an $.ajax() call every time the change event is fired! Like so:
$(document).on('keydown','input',function(){
$.ajax({
// options here
});
});
Whilst the above will help achieve what you want, I must advise that it is not great practice to fire off constant AJAX requests as this can put a huge load on the server if you have a lot of traffic. You would be better off either validating every n seconds, or validating client side, or validating on submission...
UPDATE
It appears you do not want to catch the change event, you would like to know when anything is entered. Resultantly, I have changed my code to catch the keydown event. This will fire whenever a key is pressed down whilst focused on an input.
$('#yourInputId').keyup (function () {
$.post('http://yoururl.com', { value: $(this).val() }).done(function (data) {
$('#feedbackDivId').html(data);
});
});

Hiding And Submitting A Form Using jquery

How to Hide a form and submit that form using jquery?
Is this possible?
Yes, it is possible:
On your HTML page:
<form id="my-form">
</form>
Submit
Your script:
$(document).ready(function() {
$("a#submit").click(function() {
$("#my-form").hide();
$("#my-form").submit();
});
});
If your form contains a Submit button and you want the form to be hidden when the Submit button is pressed, instead you can listen to the submit event and handle it like this:
$("#my-form").submit(function() {
$(this).hide();
return true;
});
What are you trying to do? Some scam?
You can place the form in a hidden div and using $(document).ready event, you can autosubmit the form.
Do you mean a field within a form that already has data inserted, eg. hard-coded in by you, the developer?
If this is the case, just set an id to the input field, with the value hard-coded in. Then set it's display to 'none'. Use your Jquery to interpret the data as normal.
You could also just make a variable in your jquery script, and avoid all this.
Since you've added the jquery-ajax tag, I guess you want to submit the form through AJAX. In that case you are probably looking for something like this:
$("#your-form-id").submit(function(){
$.ajax({
type: "POST",
url: "some.php",
data: $(this).serialize(),
success: function(){
$("#your-form-id").hide();
}
});
return false;
});

jQuery Forms - Ajax and normal submit the same form

I have a confirm step in one of my pages.
Desired action:
user clicks 'submit' and an AJAX request is made that does the appropriate action and returns a confirm dialog
user 'confirms' and then the form is submitted using a standard post.
So for the first part I'm fine using the jQuery form plugin:
$('form').ajaxForm(...options...);
For the second part I'd like to submit the form again, but non-ajax. Basically I want to do this:
$('form').submit();
And have it do an actual browser post. The problem is that $('form').submit() just triggers the ajax submit.
Is there a way to use the form for both purposes?
$('forms-submit-button').click()
..does that work , for the second submit?
:) :)
Can't you just unregister the submit event handler after you've ajax-posted the results? Why do you need to post the same data twice, by the way? If the data haven't changed between the Ajax post and the regular one, why is the regular one needed?
You can try to change a value in the form (se some hidden value to 1), do another ajax request and finally do a redirect. It's not the same but it should work.
Note that it's very strange to submit the same data twice though..
Answered by Surya as a comment (if you check this question again please post the answer so I can mark it!)
$('forms-submit-button').click() ..does that work , for the second submit?
form onsubmit='ajaxCheck();'
...
/form
script
var ajaxCheck = function()
{
//do check
return confirm(); // if ok form submit normaly / if cancel form doesn't submit
}
/script
or something with a flag:
var flag = true;
var firstCheck = function()
{
if( flag )
{
//do the ajax Call which will fire an event,
// let's call it onData
$.post(url,{param1:val1,...,paramN:valN},onData);
return false;
}
return true;
}
var onData = function (data)
{
flag = !confirm(...);
//if user click ok and try to re-submit the form
//this time will just go
}

Categories

Resources