Reputation: 1260
I'm starting to study web development and as exercise I was trying to make a form for redirecting in HTML with javascript and PHP.
HTML
<html>
<head>
<title>FORM</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
<form>
<input type="text" name="url"><br>
<input class="btn" type="button" id="send" value="Send" />
</form>
</body>
</html>
JavaScript
$(document).ready(function() {
$("#send").click(function(){
var url = $("#url").val();
$.ajax({
type: "POST",
url: "engine.php",
data: "url=" + url,
dataType: "html"
});
PHP
<?php
session_start();
$url = $_POST['url'];
header("Location: /".$url.");
session_destroy();
exit;
?>
The main problem is that seems that the js isn't read. Futhermore I don't know if the PHP is correct. What's wrong?
Upvotes: 0
Views: 208
Reputation: 3506
you need to add id to input
<input type="text" name="url" id="url"><br>
and also header() don't work in ajax
you need to use javascript for redirect
in php
<?php
session_start();
$url = $_POST['url'];
echo '<script>document.location.href = '.$url.'</script>';
session_destroy();
exit;
?>
and put echo text into document with ajax respond function
also you can use a better way ( with out Ajax and submit form )
$(document).ready(function() {
$("#send").click(function(){
var url = $("#url").val();
window.location.href = url;
});
here is the best answer for you How to redirect to another webpage in JavaScript/jQuery?
UPDATE: also you need delete , tags, here the html code instead of ...
<input type="text" name="url" id="url"><br>
<input class="btn" type="submit" id="send" value="Send" />
Upvotes: 1
Reputation: 30565
There's no need to make an AJAX request if you want to redirect to another URL. Also, the way your doing it at the moment wouldn't redirect anyway.
Below, when your click function fires, it will get the URL from your input field, and re-direct to that page.
<html>
<head>
<title>FORM</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_name").submit(function(event){
event.preventDefault();
var url = $("#url").val();
document.location.href = url;
});
})
</script>
<form id="form_name" name="form_name">
<input type="text" name="url" id="url"><br>
<input class="btn" type="submit" id="send" value="Send" />
</form>
</body>
</html>
Upvotes: 2
Reputation: 316
So you think your javascript isn't being executed? Does that mean you've debugged this?
If none of your javascript runs - including your ready handler, then the server isn't finding the js files. If some of your javascript is running it's possible that an error is causing it to stop. You probably just need to do a little debugging.
Upvotes: 0