2017-07-21 31 views
0

這是我的Ajax代碼,我可以很容易地提交我的表單的PHP頁面 後端如何通過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> 

現在,這裏是我的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"; 


} 




    ?> 

我要的是,當查詢sucessfull,我想我的 用戶重定向到不同的頁面使用Ajax,就像我與PHP中使用頭做 前,通過給所有neccessary URL參數,任何幫助 將非常感激牛逼

+0

你需要做的是,你已經擁有了同樣的方式在你的代碼中,使用'window.location.href = ...'。您不能在此使用服務器端重定向 - 因爲您在此處發出_background_請求,並且您在HTTP級別上執行的所有操作都在此處保持「在後臺」。因此,如果您的PHP腳本動態確定目標URL,則必須將該值傳遞迴您的AJAX腳本,然後將其指定爲新的位置。 – CBroe

+0

您可以嘗試 'window.location.replace('index.php?booking = success&booking_id ='+ id +'&user ='+ email);' 但我不是100%確定您期望看到什麼。你想添加來自Ajax響應的頭來重定向請求嗎? – inser

+0

與之前提到的問題相同,您認爲'id'和'email'來自哪裏? ;)@inser – eisbehr

回答

0

你可以只寫window.location ='你的URL';而不是「window.location.href」

-1

如果你需要通過ajax重定向到另一個頁面,那麼你必須用JavaScript或jQuery來做,你不能用php來做到這一點。你可以聽並捕獲響應echo 1;或PHP任何其他反應,然後在success回調重定向到與window.location.href="X"或類似的另一頁..

希望幫助你

0

如果你認爲idemail是來自客戶端?你需要在php端正確地返回它們,就像在json中一樣。您可以在ajax成功回調中將變量作爲response的屬性處理。

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

在客戶端使用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); 
     } 
    } 
    } 
}); 
+0

我試過了,但是它返回的空參數電子郵件和ID – loGAN

+0

當你手動調用'customerdata.php'或者你在瀏覽器網絡控制檯中看到什麼時,你會得到什麼?聽起來像你還有別的東西不工作太... @loGAN – eisbehr

+0

我編輯了代碼請檢查,實際上有一個選項,檢查電子郵件是否存在或不!我得到的是警報說明undefined – loGAN

-1

,如果你想通過動態URL的HTML,那麼你可以通過傳遞這樣做從PHP動態URL到阿賈克斯像

<?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*/ 
?> 

和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> 
+0

哦,我的上帝。最糟糕的代碼一個不必要的雙解析。不要這樣做。 – eisbehr

0

我不是PHP的專家,但嘗試: 在PHP代碼:

header('Content-Type: application/json'); 
echo json_encode(array('id' => 'your_id', "email" => '[email protected]')); 

在JS:

success: function(data) { var email = data.email; var id = data.id } 
相關問題