jQuery unexpected refresh of page when submit an AJAX form [duplicate] - javascript

This question already has answers here:
Click event doesn't work on dynamically generated elements [duplicate]
(20 answers)
Closed 6 years ago.
I have a problem, with AJAX submit of forms.
I have a piece of code like that:
$("#content").html("<form id='requestInfo'>............</form");
That put in a div with id=content the piece of code that creates a form.
I have another piece of code:
$("#requestInfo").submit(function( event ) {
event.preventDefault();
...code...
});
I would expect an execution of the code inside the submit() method where I can do my things with data of that form, but I get a refresh of the page, instead.
Does anyone know what could be the problem? It should be compatible with all browsers.
Thanks!

You are creating your form dynamically thus standard event binding will not work. You need to use event delegation
$("#content").on('submit', '#requestInfo', function(evt) {
evt.preventDefault();
});

You have to call e.preventDefault(); and return false
$("#requestInfo").submit(function( event ) {
// Code here
event.preventDefault();
return false;
});

Related

Listen for form submission [duplicate]

This question already has answers here:
add event listener on elements created dynamically
(8 answers)
Closed 6 years ago.
I need to register when a form is submitted on my site, no matter where and when - it may be dynamically loaded or created form - I need to be able to tell whenever any form is about to be submitted on the page. Event listeners are simply not an option here for the reasons mentioned above.
I was thinking what other options I have and one of them was like if I would want to capture clicks on buttons for example, I could add a click listener to the document and check event.target to determine whether a button has been clicked without adding listeners to every particular button. I was hoping I could do the same with form submissions but I didn't find a suitable event to listen for on a document.
Another solution that came to mind was to extend HTMLFormElement prototype and add a default onclick function such as
HTMLFormElement.prototype.onsubmit = function (e) {
console.log(e);
}
Unfortunately that turned out to be impossible as well, getting various errors in different browsers like
TypeError: 'set onsubmit' called on an object that does not implement interface HTMLElement.
Uncaught TypeError: Illegal invocation
I'm running out of ideas, is this impossible?
EDIT: The question is clearly not a duplicate as I have described in my first idea exactly what is stated in the accepted answer of the suggested question and I do not see how to apply this in my case.
This code will not work on snippets (because snippets don't allow form submission), so I didn't create one, but it will in your site:
$(document).on('submit', 'form', function(e) {
e.preventDefault();
console.log('Form submitted');
});
$('body').append($('<form action=""><input type="submit" value="Submit dynamic form" /></form>'));
I used the preventDefault just to make sure the form will not get submitted. You can remove it in your code.
Here is a working jsfiddle:
https://jsfiddle.net/dekelb/gr94dg7q/
update - vanilla javascript solution:
document.addEventListener('submit', function(e) {
e.preventDefault();
console.log('Form submitted');
});
$('body').append($('<form action=""><input type="submit" value="Submit dynamic form" /></form>'));
Note the relevant javascript (no-jquery) is for the submit event, it's not related to the next line (regarding adding a new form to the document).

can't interact with jquery loaded button that uses jquery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
JavaScript does not fire after appending [duplicate]
(3 answers)
Closed 7 years ago.
Working on a poll/voting system where people can click to see results before voting, and then click back again to see the options once more.
The problem is when loading in the results, the button I load to show the options again won't seem to work:
The code for them is basically the same (I've put an alert to test if it was even picking up the button, it is not):
$('.results_button').click(function() {
var poll_id = $(this).data('poll-id');
$('.poll_content').load('/includes/ajax/poll_results.php', {'poll_id':poll_id});
});
$('.back_vote_button').click(function() {
window.alert("Test");
//var poll_id = $(this).data('poll-id');
//$('.poll_content').load('/includes/ajax/poll_options.php', {'poll_id':poll_id});
});
The actual code to the back_vote_button is this for example:
<button name="pollresults" class="back_vote_button" data-poll-id="1">Back to voting</button>
Is there something I am missing about interacting with jquery loaded content?
Is your button being created after the doc is loaded? If doesn't exist at the time that the document is created, the listener is not bound. You can either bind a listener event or you can change the click to listen to an already created object, for a bad example try this:
$(document).on('click', '.back_vote_button', function(){
window.alert("Test");
});
this should work but it will listen every time you click on the body and then determine what you clicked on if this were the problem.

jquery bind event with ajax content [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
We have an external js file loaded on our static html page with a jQueryUI dialog opening a url with jQuery.load() from a button click. Inside the ajax content returned is a handful of input elements, all number type. We need to bind the keydown and change events to the number inputs, however it's not binding since the .bind() is happening before the elements are in the DOM from the ajax result. We know about .on() but having an awfully hard time wiring it up. I know we're missing something simple; any suggestions?
Basic Fiddle recreation: http://jsfiddle.net/jbwebtech/wvufLket/
There's nothing too hard to grasp that it's not already explained pretty decently inside the jQuery .on() documentation: http://api.jquery.com/on/#direct-and-delegated-events
http://learn.jquery.com/events/event-delegation/
$(staticElementParent).on("event1 event2", dynamicElement, function(){ /*stuff*/ });
In your specific case:
fiddle demo
var ajax_content = '<input type="number"><br><input type="number"><br><input type="number"><br><input type="number">';
$(function () {
console.log('jquery ready');
$("body").on('input', 'input[type=number]', function (event) {
console.log('on() input successful');
});
// "AJAX" ;)
$('button').click(function(){
$('#ajax_container').html(ajax_content);
})
});
As always, read the Docs
Can't you just put your bind the callback of the .load() function? Or if you can't(im not sure), you can change a variable in the callback and check if it's loaded in the bind.
Or you can put the bind in the file that loaded with jquery(at the end of it).
Sorry, i can't comment yet.

event.preventDefault not working on AJAX loaded content [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
This thing is driving me nuts.
So I load some simple HTML via AJAX and once it's loaded on the DOM I do this.
$('#wrap a.link').click(function(e) {
e.preventDefault();
alert("asdasdad");
});
It simply does not prevent the link from navigating to the url in the href attribute.
My syntax seems right and I've made sure the element is in the DOM and that the function finds the a.link element.
$("#wrap a.link").each(function(key, value) {
console.log("found a link"); // this shows up in the console
});
I have also tried using off() and stopImmediatePropagation() just in case some other event may be interfering, but nothing. I've also tried binding the event inside the each() loop with the same result.
What could be causing this behaviour?
Bind the events to the body for dynamic elements:
$('body').on('click','#wrap a.link',function(e) {
e.preventDefault()
});
Use event delegation:
$(document).on('click', '#wrap a.link', function(e) {
e.preventDefault();
alert("asdasdad");
});
Caution:
Keep your IDs unique.

Jquery click event after after creating div [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
hello people here is my ajax output...
$(function(){
//after ajax request
success:function(data){
$('#inbox').html('<div class="inbox_user" id='+data+'>'+data+'</div><br>')
}
})
Div is creating successfully,so Iam very sure no issues with ajax code....but now i have to give click event to class .inbox_user ,,,its not working with no error message on console... click event for #inbox works fine..... any idea to fix this??
i am trying in normal way $('.inbox_user').click(function(){})
try this :-
$(document).on('click', '.inbox_user',function(){
alert(1);
});
Demo

Categories