开发者

Have jQuery fire Ajax request when when back button is pressed

开发者 https://www.devze.com 2023-02-18 09:59 出处:网络
I have a page with 80+ dynamically generated input boxes, when the user submits the form to another .php page and one of the inputs contains a value that is not numeric, it will send them back to the

I have a page with 80+ dynamically generated input boxes, when the user submits the form to another .php page and one of the inputs contains a value that is not numeric, it will send them back to the inputs page using: &开发者_Python百科lt;?php header("Location: javascript:history.back()"); ?>, at the same time it registers the error in a session variable. The reason why I'm using javascript:history.back(), is because it stores the values that were in the form, even when you press the back button. But because it is caching the page I can't output the error in the same .php script, so I added a an element and some Ajax code. The Ajax code retrieves another file called error.php, this contains:

<?php
header("Cache-Control: no-cache"); 
session_start();
if(isset($_SESSION['error'])) 
{
    echo $_SESSION['error'];
    unset($_SESSION['error']);
}
?>

This is retrieved when the page is loaded on it own, but not when history.back() is used, it looks like the following isn't firing:

<script type="text/JavaScript"> 
 $(document).ready(function(){ 
     $("#error p").load("error.php"); 
 });
 </script>

Any ideas?

Thanks,

Justin


Using header("Location: javascript:history.back()") is generally ill-advised.

Use an absolute path i.e.

header('Location: /forms/input.php');


You could avoid submitting the form entirely and send the data via an AJAX call - the server could validate the data and send back either "success" or a list of validation errors.

If success, move on to the next URL (possibly specified alongside the success message)

If failed, modify the current page to indicate what the problems were. This avoids you having to re-create the whole form (as you never leave the page) but also allows for reliable server-side validation

0

精彩评论

暂无评论...
验证码 换一张
取 消