简体   繁体   中英

How to make a form submit only on button click not on refresh?

I have a form where i should make the form submit(request to a service) only if the form field is changed, If the field is not changed when the user refresh the page it should not submit the form again.

OBJECTIVE is to reduce the number of form submission as possible, So if the user has the same entered data and he refresh, we shouldn't waste the previous returned datas and try to give new request and show the same datas.

Instead it should be submitted only if the TEXT(searchdirectory) is changed. So there won't be repeating request for same datas.

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">            
        <label>TEXT :</label>
        <input type="text" id="search_dir" name="searchdirectory"
            value="<?php
                    if (isset($_POST['searchdirectory']))
                    {
                        echo($_POST['searchdirectory']); 
                    }
                   ?>"
        />            
        <input type="submit" value="Search" name="submit" id="searchB"/>
        <?php            
            if (isset($_POST['submit'])) 
            {
             //functions  to show results queried from searchdirectory
            }
        ?>
    </form>

I guess this would be to deal with refresh behaviour of browsers, Is there a way to stop the form submission if user refresh the page. It should show the same datas.

Use redirect when form data was sent at first.

<?php            
    if (isset($_POST['submit'])) 
    {
        //do function
        header("Location: http://". $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
    }
?>

Where "http://". $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] "http://". $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] "http://". $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] - is a link to which the user will be redirected after form submit.

There is two ways to go. But I try to address your objective, and not your specific question :)

  1. You can forward the browser to a new url after form submit. This is a very normal procedure. So that when your form submits the browser redirects immediately to a normal GET URL. Now if the user hit refresh the form is not submitted again.

2 The other approach that you should use if the form is login dialog etc. Add a one time session key to a forms hidden field, and store the same key in on the server. Now if the user submits the form check that the keys match. If they do accept the submit, and clear the key. If the user now hit F5 again, and you've already removed the key, simply reject the values submitted.

为什么在提交后不清除表单,或者为每个提交请求添加会话

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM