Search code examples
javascriptjqueryajaxloadlive

jQuery live doesn't works as expected


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:

  1. using live('click') in view_1 it launches 3 multiple XHR.
  2. using click() in view_1 it doesn't work(obviously i think).
  3. 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
               });
           }
        }
    });
}

Solution

  • 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.)