user153923
user153923

Reputation:

HTML Redirect To Root

I understand how to get a page to redirect:

<meta http-equiv="refresh" content="10; url=http://example.com/" />

I need a 10-20 second delay (shown above) to let my visitors see that their data was successfully collected.

We have the following sites:

Obviously, I do not want to change the code on my PC after it is working so that it works in the employee test environment, our change it again when it goes out to beta, or yet again before it goes LIVE.

The redirect, like the one above, would be used after someone submits a form on our website.

How would I create a redirect that knows its location?

My current task is to find out how to do this in PHP, so I might be able to write the tag before the page is served.

But, I also develop pages in ASP.NET for other customers, so I would like to see ways to do this that can be handled in Windows as well.

Upvotes: 2

Views: 5594

Answers (2)

Bluedayz
Bluedayz

Reputation: 599

In PHP:

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    header('location: /'); //or header('location: '.$_SERVER['HTTP_HOST']);
}

With jQuery setTimeout function:

setTimeout(function(){ window.location = '/'; }, 10000);  //10.000 milliseconds delay

Here you can learn more about the PHP SERVER super global and follow this link to the PHP header() function.

Using ajax to send requests to the server

If you use jQuery, you should probably think about this solution: Request the PHP file via ajax and do your database update or some serverside stuff. If it was successful, display a message and redirect after some time.

Example:

jQuery:

$('#form').on('submit', function() {
    var inputs = $(this).serialize(); //safe the submitted data
    $.post('path_to_file.php', inputs, function(data) {  //returned a json array
        var data = $.parseJSON(data);  //decode the json data
        if('errors' in data) {  //were there any errors?
            $.each(data['errors'], function() {
                $('#error-box').append(this); //show the error message
            });
        } else {  //if no errors
            $('#succes-box').html('Update was successful.');
            setTimeout(function(){ window.location = '/'; }, 10000); //Redirect after 10s
        }
    });
});

path_to_file.php

<?php
//Do something with post data.....
$response = array();
if(!$query) {
    $response['errors'][] = 'There was an error querying the database.';  //error example
}
echo json_encode($response);

Hope this helps.

Upvotes: 1

Brett
Brett

Reputation: 589

Change your redirect tag to point to the url / which will always be the root path of the domain you're on.

<meta http-equiv="refresh" content="10; url=/" />

Upvotes: 6

Related Questions