简体   繁体   中英

How to store and reload a dynamic form via cookies?

I have a form that the user can add rows to. When that form is submitted I need to store those values in cookies so I can reload the form when the page refreshes or the user leaves the site and returns. I've already got the form being built from javascript and am looking for some sort of js or php tool that will automatically store and reload forms, including dya=namic generation of forms.

Thanks!

Seems like you should be able to use jquery's built in form serializer, and then save that in a cookie.

//here's a little helper function to set a cookie

function setCookie(key, value, daysUntilExpiration) {
    var expiration = new Date();
    expiration.setTime(expiration.getTime()+(daysUntilExpiration*86400000));

    document.cookie = key + "=" + value + ";expires=" + expiration.toGMTString() + ";path=/";
}

//first, get the serialized data from your dynamic form
var formData = $("#myform").serialize();

//then, save it into a cookie
setCookie("myform", formData, 30); //cookie saved for 30 days

To pull it back out, you should be able to simply split on the key/value with the "=" as the split character, then loop through each one, and build out the form HTML.

You may use PHP's setcookie() function to save these. Here's a few simple functions to do what you want. However, this will only work with inputs that have values. It will not work with selects. Make sure each input has a different name, otherwise this will not work.

function SaveAll() {
    $cookie_expires = 14; // how many days until the cookies expire
    foreach($_POST as $col => $val) {
        setcookie("form_".strtolower($col), $val, time()+(64000 * $cookie_expires));
    }
}

function Load($item) {
    $item = strtolower($item);
    if(!$_COOKIE['form_'.$item]) return null;
    return $_COOKIE['form_'.$item];
}

if($_POST['submit_button_name']) {
    SaveAll();
    echo "All inputs have been saved! <BR><BR>";
}

Then simply add things like this to all your inputs.

<input name="Item01" value="<?=Load('Item01');?>" />

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