2013-08-05 27 views
0

之前,我有一個提交,說這個窗體上按鈕:使用JavaScript填寫隱藏輸入PHP提交

<input type="submit" name="add_submit" onclick="return getCoord()" value="Add Location" /> 

兩個隱藏輸入字段是這樣的:

<input id="long" name="long" type="hidden" value="" /> 
<input id="lat" name="lat" type="hidden" value="" /> 

腳本看起來像這樣的:

<script type="text/javascript"> 
    function getCoord() { 

     address = document.getElementById('street').value + " " + document.getElementById('city').value + " " + document.getElementById('state').value + " " + document.getElementById('zip').value; 
     console.log(address); 
     var geocoder = new google.maps.Geocoder(); 

     geocoder.geocode({ 'address': address}, function(results, status) { 

      if (status == google.maps.GeocoderStatus.OK) { 
       var latitude = results[0].geometry.location.lat(); 
       var longitude = results[0].geometry.location.lng(); 

       document.getElementById('lat').value = latitude; 
       document.getElementById('long').value = longitude; 


      } 
     }); 

    } 
</script> 

php後:

 $new_long = $database -> escape_value($_POST['long']); 
     $new_lat = $database -> escape_value($_POST['lat']); 

我希望JS函數在表單提交前填寫longlat字段的值;然後在php後,我想抓住輸入字段 - 但它返回空白。有邏輯錯誤是否有錯字?

注意:我確認地址正在正確記錄在JS控制檯中。

編輯︰我實際上得到一個數據庫查詢失敗錯誤,但它SEEMS的結果是空白longlat條目。這些座標正被放入數據庫中。

+1

@woofmeow我刪除它,同樣的結果。 – KickingLettuce

+0

嘗試獲取座標服務器端(使用服務器端API),或者阻止用戶在地理編碼完成之前提交表單。 – Musa

+0

@Musa也許只是一個自動的JavaScript監視器函數,可以在填寫所有適當的字段時獲取座標? (形式不能提交,直到地址完成) – KickingLettuce

回答

1

Google API地圖是異步的,所以在它完成之前您已經有了子表單。在服務器上執行或使用Observer嘗試。

編輯

var geoCompleted = false; 

function getCoord() { 

    address = document.getElementById('street').value + " " + document.getElementById('city').value + " " + document.getElementById('state').value + " " + document.getElementById('zip').value; 
    console.log(address); 
    var geocoder = new google.maps.Geocoder(); 

    geocoder.geocode({ 'address': address}, function(results, status) { 

     if (status == google.maps.GeocoderStatus.OK) { 
      var latitude = results[0].geometry.location.lat(); 
      var longitude = results[0].geometry.location.lng(); 

      document.getElementById('lat').value = latitude; 
      document.getElementById('long').value = longitude; 
      geoCompleted = true 
      $('#form-id').submit(); 

     } 
    }); 
    return geoCompleted 
} 
+0

工作完美,謝謝! – KickingLettuce