2017-09-23 69 views
0

這是我試圖完成的流程:AJAX後到PHP文件未返回數據在成功

形式完成 - 發送到PHP文件中的數據>數據 - > PHP文件中獲取數據,查詢API - > PHP然後將文件返回到原始頁面的查詢結果作爲echo

這個往返時間應該在10秒左右。這裏是我的表格,AJAXPHP文件。

<form id="query_form"> 
    <input type="text" id="query_input" name="query_input" required> 
    <button id="send_btn" type="submit" name="send_query" value="Submit Request"> 
</form> 

AJAX

<script type="text/javascript"> 
$(document).on("click", "button[id='send_btn']", function(e){ 
    e.preventDefault(); // Prevents any default actions by clicking submit in a form. 

    var query = $("#query_input").val(); // Gets the value of an input 


    $.ajax({ 
       type: "POST", 
       url: "run.php", 
       data: {query:query}, 
       success: function(r){ alert(r); } 
      }); 

}); 
</script> 

PHP

<?php 

require('RestClient.php'); 
$term = ""; 

    if(isset($_POST['query'])){ 
     $term = $_POST['query'] 
     try { 

     $client = new RestClient('https://api.dataforseo.com/', null, '#########', '###########'); 

     $post_array = array("language" => "en","key" => $term); // This is the term to search, correct? 

     $sv_post_result = $client->post('v2/kwrd_sv', array('data' => $post_array)); 

     $search_volume = $sv_post_result["results"][0]['sv']; 

     echo "<div id='results_div'> 
      <table id='results_table'> 
       <tr class='results_table_row'> 
        <td id='SEO_Search_Volume_Cell'> 
         $search_volume <span>Approximate Number Of Searches Per Month</span> 
        </td> 
       </tr> 
      </table> 
     </div>"; 

    } catch (RestClientException $e) { 
     echo "\n"; 
     print "HTTP code: {$e->getHttpCode()}\n"; 
     print "Error code: {$e->getCode()}\n"; 
     print "Message: {$e->getMessage()}\n"; 
     print $e->getTraceAsString(); 
     echo "\n"; 
     echo "An Error Has Occured, Please Try Again Later"; 
     exit(); 
     } 
    } 

?>

顯然數據echo'd back需要與表單顯示在同一頁面上,但沒有任何迴應。爲什麼會這樣?

+0

'header('Content-Type:application/json');'需要在輸出之前 – KDOT

+0

你能演示一下嗎?此外,我剛剛確定表單中的值不是通過ajax提交,或者b)未在php文件中收到。 – Ethan

+0

您需要'json_encode()'javascript的輸出來理解它並將其作爲內容類型'application/json'返回 - [請參閱此示例](https://3v4l.org/N6leg) – KDOT

回答

0

嘗試以「字符串」格式發佈數據,例如,

var query = $("#query_input").val(); //獲取輸入

var queryString = 'query='+ query;,然後在$就調用與使用它的值:data: queryString,

回升的與$ _ POST [「查詢」]值