2015-09-02 30 views
0

我有三個php文件。做這些事的在PHP變量中獲取Ajax腳本響應

main.php - to use stored Ajax response. 
filter.php - to send Ajax request and get response 
insert.php - to store Ajax response for using in main.php 

主要目的是使用使用PHP代碼客戶端的值,因爲服務器&客戶端不能交換變量值對方。

預期:響應應該存儲在main.php中的php變量中。

---------- ---------- main.php

?> 

<script> 
$.ajax({ 
type: "POST", 
url: "filter.php", 
data: { id1: name, id2:"employees"}, 


    success:function(response) { 
    var res = response; 
    $.ajax({ 
     type: "POST", 
     url: "insert.php", 
     data: { id1: res }, 

    success:function(data){ 
     alert(data); 
     } 
    }); 
}); 
<script> 

<?php 

$ajaxResponse = ???? <need to get value of data over here> 

-------- filter.php ----- -----

// Return employee names 

    if ($_POST['id1'] == "name" && $_POST['id2'] == "employees") { 

     $conn = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 
     if ($conn->connect_error) { 
      die("Connection failed: " . $conn->connect_error); 
     } 

     $sql = "SELECT " .$_POST['id1']. " FROM 1_employees"; 
     $result = mysqli_query($conn, $sql); 
     if (mysqli_num_rows($result) > 0) { 
      while($row = mysqli_fetch_array($result)) { 
       $rows[] = $row['name']; 
      } 
     } 

     echo json_encode($rows); 

     mysqli_close($conn); 

     exit (0); 

    } 

-------- ---------- insert.php

if ($_POST) { 

    if ($_POST['id1'] !== "") { 

     echo $_POST['id1']; 

    } 

} 

所以,我怎麼能得到主Ajax響應值.php @ $ ajaxResponse = ????。

感謝您的幫助提前!

回答

1

下面是答案:

使用以下方式main.php獲取名稱:

-------- ---------- filter.php

session_start(); //at the top 
$_SESSION['names'] = json_encode($rows); 

-------- ---------- main.php

session_start(); 
$issued_to = explode(",", $names); 

session_unset(); 
session_destroy(); 
1

你不能這樣使用它。

爲什麼:

的JavaScript/jQuery是運行在瀏覽器的時候DOM完全加載和元素都可以做出選擇的腳本語言。

雖然php是在頁面加載之前在服務器上運行的服務器端語言。

因此,總之你不能指定一個Ajax響應到一個PHP變量。


一兩件事可以做,有一個隱藏的輸入,並把響應值在裏面,你可以得到該值來使用它。

success:function(data){ 
    alert(data); 
    $('#hiddenInputId').val(data); // set the response data to the hidden input and use it. 
} 
+0

一定有什麼事情。任何選擇? –

1

要顯示的響應內容

你的情況

它是後<script>標籤

而且使用innerHTML來顯示內容

使用此代碼,您可以創建一個div

<script> 
$.ajax({ 
type: "POST", 
url: "filter.php", 
data: { id1: name, id2:"employees"}, 


    success:function(response) { 
    var res = response; 
    $.ajax({ 
     type: "POST", 
     url: "insert.php", 
     data: { id1: res }, 

    success:function(data){ 
     $("#responseContent").html(data); 
     } 
    }); 
}); 
<script> 
<div id="responseContent"></div> 

讓我知道它是否有幫助

+1

你沒有看過這個問題。我想採用PHP變量,而不是JS div或HTML。 –

+1

然後你不能在PHP變量中獲得Ajax響應 –

+0

從技術上講,你無法將當前頁面的JavaScript變量傳遞給當前頁面php。這就是爲什麼我們要去ajax。 Ajax會將JavaScript變量傳遞給另一個PHP文件 –