Lock
Lock

Reputation: 5522

Why is my code firing multiple times

I have the following which is called from a $(document).ready(function() {:

  $('#file_upload_form').submit(function(){
    // show loader [optional line]             
    //if(document.getElementById('upload_frame') == null) {
      // create iframe
      $("#upload_list_button").hide();
      $("#loading_icon_upload_addresses").show();
      $('body').append('<iframe style="display: none" id="upload_frame" name="upload_frame"></iframe>');
      $('#upload_frame').on('load',function() {
        $("#upload_frame").unbind('load');
        if($(this).contents()[0].location.href.match($(this).parent('form').attr('action'))){
          // display server response [optional line]
          var html_return = $(this).contents().find('html').html();

          if ( html_return.indexOf("Error") > -1 ) {
            $('#server_response').css("background-color", "#FFDEDE");   
          }

          if ( html_return.indexOf("Success") > -1 ) {
            $('#server_response').css("background-color", "#EEFCED");   
          }

          $('#server_response').html(html_return);

          args = {
            ajax_token : getAjaxToken(),
            client : $("input[name=client]").val(),
            address_type : address_type
          }
          loadAddressList(args);
          $("#upload_list_button").show();
          $("#loading_icon_upload_addresses").hide();
        }
      })
      $(this).attr('method','post');    
      $(this).attr('enctype','multipart/form-data');    
      $(this).attr('target','upload_frame').submit();                        
    //}
  });

I am essentially trying to upload a file by using an iframe to do the upload (found it too hard to do async).

Firebug shows that almost 100 requests are fired off. Why so? The ajax code that is firing is loadAddressList(args);

Upvotes: 0

Views: 79

Answers (2)

Rocker1985
Rocker1985

Reputation: 312

When you submit the form, the submit handler fires. Inside the submit handler (the last line of your code), you are submitting the form again. That causes another fire of submit handler, and this creates an infinite loop.

Try using e.preventDefault(); at the first line of your submit handler to make sure you submit the form only once.

Upvotes: 1

ZippyV
ZippyV

Reputation: 13018

Your code is being executed when a form is submitted but the last line of your code submits the form again.

Upvotes: 1

Related Questions