Lord Farquaad
Lord Farquaad

Reputation: 707

document.forms.submit is hanging my page

I am making a website that helps manipulate an SQL table. At the moment, I want to be able to reload my page but with some new variables. The way I've done it is by making a form (called rerouter) with a few hidden textareas and an action which is just the current page (in this instance, "connect.php"). Like so:

    <form action='connect.php' method='post' id='rerouter'>
        <input type='hidden' name='foo' id='foo'></input>
        <input type='hidden' name='bar' id='bar'></input>
        <input type='hidden' name='foobar' id='foobar'></input>
    </form>

When it comes time to reload the page I populate those textareas with the new values I'll want, then I submit the form, like this (the getRequest() calls another PHP file which just creates an SQL string and executes it. I'm just including it here to show that there's logic before the rerouting process which still executes):

    ...
    getRequest(str, succ, err);

    document.getElementById('foo').value = fooText;
    document.getElementById('foo').value = barTest;
    document.getElementById('foobar').value = foobarText;
    document.forms['rerouter'].submit();

This works great, except on occasion the whole page freezes. The only way to unfreeze it is to reload the page, then it prompts you with the "Oh, snap" error (in Chrome) which you need to reload. The getRequest() still occurs fine, but the code hangs somewhere after. I have not found a way to consistently reproduce the problem except for calling this function over and over until it finally fails, but I will keep you all informed if I discover a pattern. Also, I do not have access to jQuery.

SOLUTION: @HaukurHaf pointed out I was using an asynchronous AJAX call unstably. On occasion the PHP called by getRequest() had not finished when forms.submit() was called. I moved some code around so my main function looks like:

            ...
    document.getElementById('foo').value = fooText;
    document.getElementById('foo').value = barTest;
    document.getElementById('foobar').value = foobarText;

    getRequest(str, succ, err);

and my succ function looks like:

    function succ() {
        document.forms['rerouter'].submit();
    }

(it was empty before). Now the form won't submit until we're absolutely sure the PHP has finished executing.

Upvotes: 1

Views: 346

Answers (1)

HaukurHaf
HaukurHaf

Reputation: 13816

What is getRequest() doing? Is it doing an async AJAX call?

That basically means that the getRequest() method will not always run completely since the browser immediately tries to submit the form. This could also cause the behaviour you are describing. The correct way would be to have getRequest() accept a callback function which is executed once the request is finished. The form submit code should then be moved into that callback function.

Upvotes: 2

Related Questions