发送电子邮件php json后重定向

时间:2015-07-13 13:09:28

标签: php json redirect http-headers

我尝试重定向PHP联系表单,以便在提交后将用户重定向到新页面。我怎样才能调整以下代码来做到这一点?

我的php表单是

<?php
$servername = "localhost";
$username = "myusername";
$password = "password";
$dbname = "mydatab";
header('Content-Type: application/json');
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$user = $conn->real_escape_string(htmlspecialchars(trim($_POST['post_kod'])));
$query = "SELECT `kod` FROM `posts` WHERE `kod` = '$user'";

$result = $conn->query($query);
if($result->num_rows > 0) {

echo json_encode(array('returned_val' => 'Code is already use!'));
}
else 
{
$result = $conn->query("SELECT * FROM kodovi WHERE special = '".$user."'");
if($result->num_rows > 0) 
{


$sql = "INSERT INTO posts (pravno, ime, prezime, email, kontakt, kod )
VALUES ('$_POST[post_pravno]', '$_POST[post_ime]', '$_POST[post_prezime]', '$_POST[post_email]', '$_POST[post_kontakt]', '$_POST[post_kod]')";
if (mysqli_query($conn, $sql)) {

$to = $_POST["post_email"];
$subject = "GOOD";
$post_ime="$_POST[post_ime]";
$post_kod="$_POST[post_kod]";
$message = "
<html>
<head>
<title></title>
</head>
<body>
<p>HELLO</p>
</body>
</html>
";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <contact@mysite.com>' . "\r\n";

mail($to,$subject,$message,$headers);



echo json_encode(array('returned_val' => 'Thanks!'));
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
}
else
{
echo json_encode(array('returned_val' => 'Code is not valid'));
}

}

如果json返回(谢谢!)我想重定向到google.com

index.php中的

我有

$("#enableButtonForm").submit(function(event) {


    event.preventDefault();

$("#content-info-inner").css({ display: "block" });


    $("#content-info").html('');


    var values = $(this).serialize();


    $.ajax({
        url: "send_post.php",
        type: "post",
        data: values,
        success: function(data) {

     $("#content-info").text(data.returned_val);
},
        error:function(){
            alert("failure");
            $("#content-info").html('There is error while submit');
        }
    });
});

2 个答案:

答案 0 :(得分:0)

<强> PHP

header("Location: http://www.google.com");

echo '<script>window.location.href = "http://www.google.com";</script>'; 

<强> JS

window.location.href = "http://www.google.com";

答案 1 :(得分:0)

更改了此行

echo json_encode(array('returned_val' => 'Thanks!'));

有了这个

$response = array(
'returned_val' => 'Thanks!',
'redirect' => 'http://www.domain.com' // Here you can add URL on which you wants to redirect the page.
);

echo json_encode($response);

在此行之后的ajax成功函数中添加另一行

$("#content-info").text(data.returned_val);

添加此行以使重定向正常工作

window.location.href = data.redirect;