jQuery live doesn't works as expected - javascript

i have problems with ajax requests and simple <input type="submit"/>.
i use to load views inside other views, modular i mean, with jquery using .load(url) from one view to another.
so the problem is that if i load view_2 inside view_1 and the js script for view_2 is inside view_1 i need to use live('click') for example to launch an xhr request from view_2, so when i try it launches 3 (multiple) xhr at same time, instead of only 1 at time, don't know why.
the only thing i know is:
using live('click') in view_1 it launches 3 multiple XHR.
using click() in view_1 it doesn't work(obviously i think).
using click() directly inside view_2 it works (but i can't use js
in loaded views, i can use js only in "parents" views)
the functions are really simple, really don't know why i have this problem (i also disabled submit in ajax beforeSend) check this is a view_1 code which runs on loaded view_2 and launches 3 XHR for click :|
$(document).ready(function(){
$('#save-doc').live('click',function(){
var _title = $('#doc-title').val();
var _doc = $('#doc-doc').val();
update_doc(url_update_doc,{'title':_title,'doc':_doc,'id_doc':_choosed_doc,'id_project':id_project},this);
});
});
function update_doc(_url,_data,_starter){
$.ajax({
type:'POST',
data:_data,
url:_url,
dataType:'json',
beforeSend:function(){
$('.ajax-loading').show();
$(_starter).attr('disabled','disabled');
},
error:function(){
$('.ajax-loading').hide();
$(_starter).removeAttr('disabled');
},
success:function(json){
$('.ajax-loading').hide();
$(_starter).removeAttr('disabled');
if(json.error){
$('#error-title').html(json.error_title);
$('#error-doc').html(json.error_doc);
$.scrollTo('.append-form-edit-doc','fast');
}
if(json.confirm){
$.scrollTo('#top','fast');
$.gritter.add({
title:'Document Saved',
text:json.confirm
});
}
}
});
}

If that's a submit button inside the form then unless you prevent the default action, the form will be submitted. (That'd account for 2 POSTs, but not three.)

Remember that .live() is binding the event handler to the document itself. With that in mind, it is searching for #save-doc throughout the document on every click.
If there are multiple elements in the document with the 'save-doc' ID then they'll all be triggered.
However, what I bet is happening to you is you may have multiple forms layered which are all being executed by this one input.
Edit: Third possibility, is what Pointy mentions. Executing a submit via your event handler and another submit occurring because of browser behavior.
Please provide the HTML and what is being loaded into them.

Related

jQuery losing reference to Form

I've got a form that is submitted via ajax and is then updated by the response.
Before the submit takes place I execute the following code which works the first time but after that on the second submit, the code does not execute.
$(document).ready(function(){
$('.edit_customer').submit(function(event) {
console.log("test");
if(document.getElementById("sameAsBilling").checked == true){
$("#customer_addresses_attributes_1_line_1").val($("#customer_addresses_attributes_0_line_1").val());
$("#customer_addresses_attributes_1_line_2").val($("#customer_addresses_attributes_0_line_2").val());
$("#customer_addresses_attributes_1_city").val($("#customer_addresses_attributes_0_city").val());
$("#customer_addresses_attributes_1_state").val($("#customer_addresses_attributes_0_state").val());
$("#customer_addresses_attributes_1_zip_code").val($("#customer_addresses_attributes_0_zip_code").val());
}
});
});
I've also tried changing the listener to this:
$(document).on("submit", ".edit_customer", function(){ console.log("test");});
This code doesn't execute at all.
One thing to note is I am using Ruby on Rails which uses Rails UJS. I'm not sure why the second line of code isn't solving the issue. Any help is appreciated.
Thanks in advance.
UPDATE:
I have another element in my form that I use to fire JS using the same type of code and it works fine everytime. Here is the code:
$(document).on('click', '#qb-customers-btn', function(){
//code here makes an ajax call and loads in data
});
<span class="input-group-text bg-success text-light" id="qb-customers-btn">Load</span>
Update:
I ended up abandoning this and just used a button click listener, but now I am back with the same exact problem on a different form on a different page. I've tried everything I can think of. The only thing that works at the moment is wrapping the listener in an init function, calling init on document.load and then calling init again after the ajax has erased and reloaded the form on the page.

Commenting System - Showing posted comment without page reload

working on a commenting system using PHP.
Everything works, the insert, the validation and also the ajax call.
Currently i am doing a .load() on the container that holds the page content.
However, this causes issues when trying to post comments again. The javascript doesnt work, some of the javascript functions linked with the comments also dont work and little things like that.
How should i be dealing with comments, every time a user posts one.
Like on facebook for example, you post a comment and the new one is just placed underneath the last.
The only thing i can think of i using .append() and appending the new comment to the list.
In my PHP page i could set a JSON return of the username, the comment, the users profile picture etc and then append all of that data back?
Otherwise is there a better method of simply 're-loading' the div container after the success ajax call?
Thanks, what i have works... but i want to be learning things the CORRECT way.
Craig.
You can use $.ajax to load new comments and use .append() or prepend() to insert the new comments in the container. If you wrap the call in a function you can call the function over and over (for instance every 2 seconds) to check for new comments.
If I remember correctly .load() will only execute when the element is ready after browser refresh.
What things are not working? Remember that events and data must be bound after succesful AJAX call. Meaning if you bound events to links when the page loaded they are obviously still in effect. But if you insert a link later on it does not have any events.
What I would normally do is something like this:
$.ajax({
url: 'ajax.php',
data: { 'parameters': 'yada yada' },
dataType: 'json',
success: function( data ) {
$('.links').unbind().click(function() { alert('hello!'); });
}
});
The reason for the .unbind() is that you will otherwise bind several events on the existing links - and you don't want that ;-)

Callback when web page download completes

When the user click on a tab in a web page, the tab opens and its corresponding page downloads from the server.
I want to add some UI in this page through JavaScript or jQuery. I know how I can add this but problem is if I execute my JavaScript function for adding UI on click of the tab, it does not work because the corresponding page has not been downloaded yet.
Basically, what I want to know such function that is called when the page completely downloads.
Have you used JQuery success ?? success handler will be called only after your response is ready.
Try this :
$.ajax({
url: "test.html",
context: document.body,
success: function(){
//Do the stuff here, hence downloading has been completed and response from server is ready
$(this).addUI("done");
}
});
add this in the body of your page..
<body onload="init()">
</body>
Basically your calling your init function -- which initiates all the other functions which you want only after the body of the webpage is loaded..
I have face this problem too.. Problem here is your content is not yet available before you could work on it.
any reference you give will result in returning Null
The solution can be .bind() & .live()
suppose this is your dynamic content
$('body').append('<div class="clickme">Another element</div>');
you can bind the element by,
$('.clickme').bind('click', function() {
// Bound handler called.
});
or register it for live content, by
$('.clickme').live('click', function() {
// Live handler called.
});
when no longer needed, you may unsubscribe the event on dynamic content by .die()
you may also find .delegate() & undelegate() useful as there are little issues with .live() & .die().
Check http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/ for choosing the one you need for your application.
Remember not to forget you ensure that content is loaded by ajax success as programmer_1 here, mentioned.
Good luck :)
Any further clarifications pls comment.

CKEditor submitting empty content to the form.

I've started using CKEditor v3 few weeks ago.using it in a php project.i've been using it with jquery (using jquery adapter) and all this while using $.ajax (because can't handle for errors when using jquery form) to submit and i thought everything was alright .
So here pops up a case where i need to use normal form mechanism to submit the ckeditor content and all the other information of the form.
To my surprise the content was empty so i started google and apparently it's a known issue.
i haven't seen any thing YET that could let me post my content to php side. so i've come up with a workaround.
I know onclick will always fire before the onsubmit so i've written this.
function returntoSubmit(){
myForm = document.forms[0];
myForm.elements["content"].value = $("#content").val();// note that the textarea name and id are all the same "content"
}
// html here
<input type="submit" value="Save" onclick="returntoSubmit()" />
that does the work for me.But truly and a little uncomfortable with this, isn't there any better method to solve this issue?
Thanks
I'm running a large application with some nasty legacy code and needed something that worked across the whole app as non-intrusively as possible. In my case it wasn't feasible to listen for submits on each page individually, and even when I did I occasionally had race conditions where the submit still occurred before the click event code had a chance to do it's thing. The following seems to do the trick for me when ran after page load at a global scope:
for(var i in CKEDITOR.instances) {
CKEDITOR.instances[i].on('blur', function() { this.updateElement(); });
}
May this help
CKEDITOR.instances[content].getData()
Just ran across this problem too... it seems that the best way to update all the textareas is:
for(var i in CKEDITOR.instances) CKEDITOR.instances[i].updateElement();
http://cksource.com/forums/viewtopic.php?f=11&t=15877
I have actually added my own twist that works nicely as I was having trouble today with the same issue.
I used your function call, but instead do this i give my textarea the ID of ckeditor:
function returnToSubmit() {
$('#ckeditor').val(CKEDITOR.instances['ckeditor'].getData();
}
I used this in a jquery ready event for all forms:
$('form').on('submit',function(){
for(var i in CKEDITOR.instances) {
CKEDITOR.instances[i].updateElement();
}
});
Later I add another specific form submit event handler to do the actual custom submit logic for each form.

Ajax and Fancybox form redirecting

So I had the bright idea to use fancybox and jquery to send a form via AJAX. The form actually displays quite nicely. However when the form is submitted, the user is always redirected. I've tried to mitigate this several ways but to no avail. It's been a while since I've used jQuery so it may be something stupid. I can't for the life of me figure out what's going wrong.
Here's the code, to the best of my knowledge it should prevent the form from redirecting:
$('#fancybox-wrap #email_form').bind('submit', function(){
$.fancybox.showActivity();
var form_data = $(this).serialize();
form_data[crap] = 'Crap';
$.ajax({
type : "POST",
cache : false,
url : "<?php echo site_url('inventory/email'); ?>",
data : form_data,
success: function(data) {
$.fancybox(data);
}
});
return false;
});
If there are any better ways to do this I would glad to hear them. Thanks!
(This answer stems from the discussion between myself and MackDaddy in the comments of the question.)
The problem here is not that Ajax or Fancybox has interrupted the intended flow of the form (stopping it from following its action), but rather simply that:
The selector is wrong, since div#email_form is not the form itself, but rather its container, and therefore cannot take a submit event; and
Fancybox appears to remove the div and replace it elsewhere inside its own containers. Therefore, the use of the bind function does not work as expected, since the element it attaches to is removed from the DOM and a duplicate is inserted. The live function should be used instead, since it will attach the event not only to the first #email_form, but all subsequent ones that are inserted into the DOM.
Have you tried action="javascript: void(0)" in your form?

Categories

Resources