I have the following in my HTML:
<input type="text" name="code" />
<input type="submit" value="Submit" />
What I want to do is to redirect the user to page1.html
when s/he enters, let's say, 12345 and redirect him/her to page2.html
when s/he enters 56789. How may I do this with PHP? I'm okay with using JavaScript as well.
Let me rephrase that (just in case).
I want to write 12345 in the input field, and after clicking the Submit
button, to be redirected to page1.html
. The same principle for 56789 and page2.html
.
I found this old jQuery code of mine and changed it a bit. I'd be glad to hear your suggestions to polish it and achieve what I want.
$('input').keyup(function () {
var val = $(this).val();
var newVal = val.split('1234').join('HELLO');
if (newVal !== val) {
window.open("http://localhost:8000/page1.html");
}
});
Additionally, is this right (for PHP)? (didn't try it yet)
if ($_POST['code'] == '1234'){
header("Location: redirect_to_me.php");
}
Please bear with me as I am yet a fledgling in this field.
Thank you.
Try this
$(document).ready(function(){
var pages = {
"123456" : "page1.html",
"56789" : "page2.html",
"5252" : "page3.html"
}
$('input[type=submit]').click(function (e) {
e.preventDefault();
var val = $('input[name=code]').val();
var page = pages[val];
window.location = page;
});
});
Check your form submission (_POST or _GET) then redirect depending on the value of 'text'. Just remember, you can only do a Location redirect when no output has been sent to the browser.. ..and always 'exit' after.
if(isset($_POST)){
if($_POST['text'] == '12345'){
header ("Location: page1.html");
exit;
} elseif($_POST['text'] == '6789'){
header ("Location: page2.html");
exit;
}
}
To do this in PHP;
<form action="file.php" method="POST">
<input type="text" name="code" />
<input type="submit" value="Submit" />
</form>
And your file.php
using a switch
statement;
switch($_POST['code']):
case '123456':
header('Location: page1.html');
break;
case '56789':
header('Location: page1.html');
break;
case '5252':
header('Location: page3.html');
break;
default:
header('Location: codenotfound.html');
endswitch;
Or a more elegant solution;
$page = 'codenotfound.html';
$pages = array(
'123456' => 'page1.html',
'56789' =>'page2.html',
'5252' => 'page3.html'
);
if(isset($pages[$_POST['code']])):
$page = $pages[$_POST['code']];
endif;
header('Location: ' . $page);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With