Question

I've written this code to try and send a url as a post value to the same page. The code worked great in chrome and safari... but fails in FF3 and IE (the last one I could care less about, but I need it to work in firefox). In FF3 and IE it opens up a blank new tab. What should I know about the differences between the way webkit and the other browsers handle form submital via javascript?

The code I'm using is this:

function posturl (url) {
        var myForm = document.createElement("form");
        myForm.method="post" ;
        var myInput = document.createElement("input") ;
        myInput.setAttribute("name", "url") ;
        myInput.setAttribute("value", url);
        myForm.appendChild(myInput);
        document.body.appendChild(myForm) ;
        myForm.submit();
        document.body.removeChild(myForm) ;
    }

EDIT: Maybe I should add that the way it's working is that I'm using the script as a href in my anchor tags. So when you click on the link it passes the parameter through the post to the same page, updating the content accordingly.

Was it helpful?

Solution

It works for my Firefox 2, Chrome 2. Here is my complete test page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <script>
    function posturl (url) {
        var myForm = document.createElement("form");
        myForm.method="post";

        var myInput = document.createElement("input") ;
        myInput.setAttribute("name", "url") ;
        myInput.setAttribute("value", 'http://www.google.com');

        myForm.appendChild(myInput);
        document.body.appendChild(myForm);
        myForm.submit();
        document.body.removeChild(myForm);
    }
    </script>
</head>
<body>
<input type="button" value="posturl()" onclick="posturl()" />
</body>

There must be something else (possibly related to opening blank tabs?? WTF?) that is breaking your code.

Here's why it doesn't work in IE.

OTHER TIPS

That should work across browsers.But actually I just think you need a window.setTimeout here with a value of 0. What's happening is that you're trying to access an element before JavaScript has a time to "breathe"

Try:

window.setTimeout( function() { 
        myForm.submit();
        document.body.removeChild(myForm);
}, 0 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top