user2947725
user2947725

Reputation: 41

How do I check if a CGI button is pressed and then redirect them

It's hard to explain but for example. If I have something like this:

print submit(value => Exit), "\n";

how do I make it so that when the person presses that exit button in the browser, it will redirect them to a page that says for example "cya later".

Upvotes: 0

Views: 734

Answers (2)

Dave Cross
Dave Cross

Reputation: 69264

You're using the HTML generation functions from CGI.pm. These have been deprecated for some time (and they were never a good idea). I recommend that you look at using a templating engine instead.

Having said that, the changes the you require are pretty simple. You'll need to change your code in two places. Firstly, you need to change the code that generates the submit button so that it adds a name to the generated HTML.

# Don't do this. Use a template.
# NB: Note the '-' I've added to the option names.
print submit(-value => 'Exit', -name => 'Exit'), "\n";

Then you'll need to change the code which deals with your incoming parameters to deal with this new parameter.

if (param('Exit')) {
  print redirect('http://somewhere_else.com/');
  exit;
}

Note that a) the redirection header should be printed instead of any other headers that you program might be planning to return (so, don't include a content-type header) and b) your program should exit soon after printing the redirection header - you shouldn't print any other output.

Update: It's also worth pointing out that one of the reasons for avoiding the HTML generation functions is that they are (necessarily) over-complicated to use. A good example is your usage of them:

print submit(value => Exit)

This is actually wrong as it produces this output:

<input type="submit" name="value" value="Exit" />

What I suspect you meant was:

print CGI->new->submit(-value => 'Exit')

Which gives this:

<input type="submit" name=".submit" value="Exit" />

As you haven't given an explicit name, the function has synthesised one (.submit) for you. In my example above I have given the input an explicit name:

print submit(-value => 'Exit', -name => 'Exit')

Which produces this:

<input type="submit" name="Exit" value="Exit" />

Upvotes: 1

Quentin
Quentin

Reputation: 943585

Give the submit button a name. It will then appear in params if it is used to submit the form.

Upvotes: 0

Related Questions