简体   繁体   English

如何通过php中的ajax重定向到其他页面

[英]how to redirect to different page through ajax in php

this is my ajax code ,I can easily submit my form to php page in backend 这是我的ajax代码,我可以轻松地将我的表单提交到后端的php页面

  <script type="text/javascript">
$("#contact-form").submit(function(e){
  e.preventDefault();
  $.ajax({
    url: 'customerdata.php',
    async: true,
    cache: false,
    data: $('#contact-form').serialize(),
    type:'post',
      success: function(response) {

        document.getElementById("loader").style.display = "none";

        if( response.hasOwnProperty('id') ) {
            window.location.href = 'index.php?booking=success&booking_id=' + response.id + '&user=' + response.email;
        }




       }
});
});




</script>

Now here is my php code , 现在这是我的php代码,

    <?php
    $name=trim(htmlspecialchars($db -> real_escape_string($_POST['name'])));
$mail=trim(htmlspecialchars($db -> real_escape_string($_POST['email'])));
$phone=trim(htmlspecialchars($db -> real_escape_string($_POST['important_number'])));
$booking="ZOHO".crypto_rand_secure(10000,100000);
$typeofcab=trim(htmlspecialchars($db -> real_escape_string($_POST['the_cab'])));
$alt=trim(htmlspecialchars($db -> real_escape_string($_POST['alternate_number'])));
$drop=trim(htmlspecialchars($db -> real_escape_string($_POST['drop_address'])));
$pickup=trim(htmlspecialchars($db -> real_escape_string($_POST['pickup_address'])));
$source=trim(htmlspecialchars($db -> real_escape_string($_SESSION["source"])));
$destination= trim(htmlspecialchars($db -> real_escape_string($_SESSION["destination"])));
$type=trim(htmlspecialchars($db -> real_escape_string($_SESSION['type']))) ;
$date=trim(htmlspecialchars($db -> real_escape_string($_POST['journey_date'])));
$gotime= trim(htmlspecialchars($db -> real_escape_string($_SESSION["time"])));
$price= trim(htmlspecialchars($db -> real_escape_string($_SESSION["price"])));
$status="Pending";
$takenby="Pending";
$avail="Pending";
$driver="Pending";
$carnumber="Pending";
$password=$phone=trim(htmlspecialchars($db -> real_escape_string($_POST['important_number'])));
$need=trim(htmlspecialchars($db -> real_escape_string($_POST['need'])));
$vendorprice = price($price);

if(!isset($_POST['return_date'])){
    $return='NOT APPLICABLE';
    $returntime='NOT APPLICABLE';


}
else {
  $return=$_POST['return_date'];
    $returntime=$_SESSION["timeo"];
}



$stmt=$db->prepare("SELECT  `email` FROM `users` WHERE email=?");
$stmt->bind_param("s",$mail);
$rock=$stmt->execute();
$stmt->bind_result($email);
while($stmt->fetch()) {
}



if($email !=$mail)
{

$query=$db->prepare("INSERT INTO  `customerdata`( `vendorprice`,`price`,`name`, `email`, `phone`, `bookingid`, `source`, `destination`, `sourceaddress`, `destinationaddress`, `alternate`, `typeofjourney`, `journeydate`, `returndate`, `journeytime`, `returntime`, `status`, `availability`, `takenby`, `cabtype`, `drivername`, `carnumber`, `customerneed`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");


$query->bind_param("sssssssssssssssssssssss",$vendorprice,$price,$name,$mail,$phone,$booking,$source,$destination,$pickup,$drop,$alt,$type,$date,$return,$gotime,$returntime,$status,$avail,$takenby,$typeofcab,$driver,$carnumber,$need);
$run=$query->execute();


$query_user=$db->prepare("INSERT INTO `users`(`password`,`email`, `phone`, `bookings`,`name`) VALUES (?,?,?,?,?)");
$query_user->bind_param("sssss",$password,$mail,$phone,$booking,$name);
$run_query=$query_user->execute();
$mailsent=sendmail($name,$mail,$booking,$type,$date,$gotime,$source,$destination,$price,$password,$typeofcab);





if ($run && $run_query ) {
  echo json_encode(array("id" => $booking, "email" => $email));

  // session_destroy();
  //header('Location: index.php?booking=success&booking_id='.$booking."&user=".$email."price=".$price."phone=".$phone);
//exit;
}
else {
  echo json_encode(array("error" => mysqli_error($db)));
//  echo("Error description: " . mysqli_error($db));
  // header('Location:index.php?failed');
  // exit;


}

}


else {

//  $yourURL="bookingconfirmation.php?route=oneway";

//echo ("<script>alert('This email already exists with us,please try different email'); location.href='$yourURL'</script>"); // redirect with javascript, after page loads
echo json_encode(array("failed" => $email));
//echo "this email already exists";


}




    ?>

What I want is ,when the query is sucessfull ,i want to redirect my user to different page with ajax ,like I was doing with php before using headers ,by giving all the neccessary url parameters ,any help will be really appreciated t 我想要的是,当查询成功时,我想使用ajax将用户重定向到其他页面,就像我在使用标头之前使用php一样,通过提供所有必要的url参数,任何帮助将不胜感激

you can write only window.location='You URL'; 您只能写window.location ='您的URL'; instead of "window.location.href" 而不是“ window.location.href”

Where do you think that id and email are coming from on client side? 您认为idemail来自哪里? You need to return them correctly on php side, like in a json . 您需要在php端正确返回它们,就像在json Than you can handle the variables as properties of response in the ajax success callback. ajax成功回调中,您可以将变量作为response属性来处理。

<?php
if( $run && $run_query ) {
    echo json_encode(array("id" => $booking, "email" => $email));
}
else {
    echo json_encode(array("error" => mysqli_error($db)));
}

On client side use the response object, there are no variables passed as parameters, only as properties: 在客户端使用response对象,没有作为参数传递的变量,仅作为属性传递的变量:

$.ajax({
    url: 'customerdata.php',
    cache: false,
    data: $('#contact-form').serialize(),
    dataType: 'json',
    type: 'post',
    success: function(response) {
        document.getElementById("loader").style.display = "none";

        if( response.hasOwnProperty('id') ) {                
            window.location.href = 'index.php?booking=success&booking_id=' + response.id + '&user=' + response.email;
        }
        else {
            alert(response.error);
        }
     }
   }
});

I'm not an expert in PHP, but try: in php code: 我不是PHP方面的专家,但是请尝试:在php代码中:

header('Content-Type: application/json');
echo json_encode(array('id' => 'your_id', "email" => 'test@email.com'));

in js: 在js中:

success: function(data) { var email = data.email; var id = data.id }

if you need to redirect to another page via ajax then you have to do it with javascript or jquery ,, you can't do it with php. 如果您需要通过ajax重定向到另一个页面,则必须使用javascript或jquery进行操作,则不能使用php进行操作。 you can listen and capture response echo 1; 您可以收听和捕获响应echo 1; or any other response from php and then in your success callback redirect to another page with window.location.href="X" or similar.. 或来自php的任何其他响应,然后在您的success回调中使用window.location.href="X"或类似名称重定向到另一个页面。

hope that helps you 希望对您有帮助

if you want to pass dynamic url to html then you can do this by passing dynamic url from php to ajax like 如果您想将动态网址传递给html,则可以通过将动态网址从php传递给ajax这样来实现

<?php
if ($run && $run_query ) {
  echo $booking;
  echo $email;
    $return['url'] = "index.php?booking=success&booking_id=".$booking."&user=".$email."price=".$price."phone=".$phone;
   $return['err_msg']  = '';
}
else {
    $return['url'] = '';
    $return['err_msg']  = "Error description: " . mysqli_error($db));
}
 echo json_encode($return);/* encode json data to get in html file*/
?>

and javascript code could be like this 和JavaScript代码可能是这样的

<script type="text/javascript">
$("#contact-form").submit(function(e){
  e.preventDefault();
  $.ajax({
    url: 'customerdata.php',
    async: true,
    cache: false,
    data: $('#contact-form').serialize(),
    type:'post',
      success: function(data) {
            console.log(data); /*see server msg */
           var pd = JSON.parse(data); /*decode json data*/

           location_url = pd.url; 
        if (pd.url !='') {
             document.getElementById("loader").style.display = "none";
             window.location.href = location_url;
        }
        else {
           var err_msg = pd.err_msg;
           if(err_msg != ''){
              $('#error').html(err_msg);
           }
            document.getElementById("loader").style.display = "none";
        }
         },

     error: function(xhr, ajaxOptions, thrownerror) { }

       }
  });
});

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM