Search code examples
javascripttokenform-submittruncated

form.submit() truncating string with '?'


I have a JavaScript function :

function post(aAction) {
    var form = document.createElement("form");
    form.action=aAction;
    document.body.appendChild(form);
    form.submit();
    alert(form.action);
}

( I'm an experienced developer but not much experience with JScript - lifted that post() function from some website. )

I am passing this string into the function: A URL with query information:

http://testServer:3072/aQuerySite.dll/GetErrors?server=server1:5678

This URL returns a page listing error messages from the specified server: "server1:5678" - an argument passed to a server side query as

server=server1:5678

in the URL.

If I paste that URL directly into a browser and post it, the correct page with appropriate data is returned, and the browser address shows the complete URL as it was sent.

But when I pass the URL into my function, I get back a correctly formatted page but no records, and the browser address shows the URL truncated after the ? token :

http://testServer:3072/aQuerySite.dll/GetErrors?

The page returns showing no records because the query parameters after ? never got to the server for evaluation - query runs looking for nothing.

alert(form.action) in the function, which I added for debugging, shows the correct URL with query arguments, as does my debugger (WebStorm) and as mentioned, if I hit the URL directly from the browser, I get the correct result. I can only conclude that my URL is getting truncated in the form.submit() call.

This happens in IE, FireFox and Chrome. I also tried using ? for "?" - same result.


Why is this happening? How can I fix it?


Solution

  • It seems like you're trying to use a newly created form to redirect a user through its submission.

    That is not necessary, as you can simply redirect the user using the following:

    window.location = 'your_url';
    

    In your case, you say that the querystring is being replaced with a simple ?.

    That's because you created a form, and this form uses GET to post its data.

    So if the form action is https://www.stackoverflow.com, the query string will be added with a interrogation following by the key/value pairs.

    Let's suppose you have a form with two inputs named a and b, when you submit them, the query string would look like this:

    https://www.stackoverflow.com?a=zzz&b=zzz
    

    If you simply put this url in your form action, it will replace the query string with its own data when you submit it. Since your form has no named inputs, the query string will be empty, that's why you have an empty ? after the url.