简体   繁体   中英

How can I sometimes redirect before a form post?

I have a form which is in a sidebar, and shows on multiple pages. If the user is on page-a.php and submits the form, it uses ajax to return some data to a div on that page.

However, if the user is on page-b.php and submits the same form (again, it is included on both pages), I want the form to redirect to page-a.php and then use the same ajax post to load the data. How can I achieve this?

Edit for clarity:

page-a.php - when this submits this form (included from separate file), an ajax call is made to page-c.php, which loads data into the div:

<form method="post" action="page-c.php">
    <input ....
               />
</form>
<div></div>

page-b.php has the exact same form (included from a separate file), but different content, so in order to load the data into the div, we need to redirect to page-a.php:

<form method="post" action="page-c.php">
   <input .....
          />
</form>

So how can I make the form call work the same (ajax that is already implemented), but have it redirect me to page-a.php first?

How about having page-b.php's form post to page-a.php, then based on the HTTP_REFERRER cgi environment variable's contents, include some javascript to do you ajax post routine on page load?

If you do a real HTTP Redirect, you will lose all of your form data that was filled in on page-b.php. If they were on the same server, I suppose you could save the data locally and associate it with a session variable, prior to the Http Redirect response. The page-a.php would check for the local form data when it loaded.

Can't you just extract that JavaScript from page-a.php into a separate .js file that is included in both page-a.php and page-b.php ? Then when the form is submitted it'll just use the same function. Update that function to take as a parameter the page that is making the call, so that you don't update the div on page-b.php .

Have your form tag set as so

<form action="page-a.php" method="post">
    <input name="formfield" id="formfield" />
</form>

on page-b.php you could use php to pull the posted data from the form.

<?php echo $_POST['formfield'];?>

You wouldn't need to use javascript/ajax for any of this.

Solved it using this:

<form name="formA" id="formA"  method="post" 
            <?php if(curPageName() == 'page-a.php'){
                echo 'class="ajax" action="page-c.php"';
                }
                else {
                echo 'action="page-a.php"';
                }
            ?>
        >

with this on page-a.php to auto submit the form on page load, which redirects the load to the ajax submit

<script type="text/javascript">$(document).ready(function() {document.formA.submitbutton.click(); });</script>

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