2017-03-18 121 views
1

我有一個Leaflet地圖和一個文本輸入。我想從文本框中獲取地址,通過PHP腳本運行它,並通過jQuery獲取結果。使用jQuery/AJAX獲取並顯示PHP的結果

這裏是我的形式:

 <form id="mapcheck" method="POST" action="geo.php"> 
      <input id="largetxt" type="text" name="checkAddress"> 
      <input id="button" type="submit" name="submit" value="Check"> 
     </form> 

這裏是PHP的一部分:

<?php 
      if (isset($_POST["checkAddress"])) { //Checks if action value exists 
      $checkAddress = $_POST["checkAddress"]; 
      $plus = str_replace(" ", "+", $checkAddress); 
      $json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $plus . '&key=GMAPSKEY'); 
      $obj = json_decode($json); 
      $mapLat = $obj->results[0]->geometry->location->lat; 
      $mapLng = $obj->results[0]->geometry->location->lng; 
      $coords = ('' . $mapLat . ', ' . $mapLng . ''); 
      return $coords; 
     } 
    ?> 


And the jQuery: 

$(document).ready(function() { 
    $("#button").click(function(){ 
     $.ajax({ 
      url: "geo.php", 
      method: "POST", 
      data: { 
      checkAddress: $("#largetxt").val() 
      }, 
      success: function(response){ 
      console.log(response); 
      } 
     }); 
    }); 
}); 

我要聽上提交通過jQuery(不是PHP)的形式,通過一個運行geocode腳本,然後把這個結果通過普通的JavaScript(Leaflet map)。通過使用jQuery的AJAX特性,我毫無用處。有一個非常簡單的解決方案,但我還沒有弄明白。

更新:問題已解決,謝謝Vic。

+0

什麼是您的完整的JavaScript代碼? –

+0

你用這個試過了什麼? – hassan

回答

0

你需要AJAX。刪除form元素但保留輸入。

$("#button").click(function(){ 
    $.ajax({ 
     url: "geo.php", 
     method: "POST", 
     data: { 
      checkAddress: $("#largeText").val() 
     }, 
     success: function(response){ 
      console.log(response); 
      //your script 
     } 
    }) 
}); 
+0

剛剛意識到我使用的是名稱而不是我的jQuery的ID。但是,我仍然有問題。我更新了主要帖子。 –

+0

@TJW我需要更多的細節。如果你的AJAX腳本工作正常,那麼我不知道你的問題到底是什麼。 – Vic

+0

該腳本不起作用。它什麼都不做。我不知道錯誤在哪裏,我不知道如何調試它。不過謝謝你的回覆。 –