将javascript变量值发送到不同页面上PHP中的sql查询



我有两个元素。自动搜索栏和Map(mapbox gl(

  • 我想加载id被搜索的用户的位置
  • 我为每个用户获得相同的标记(位置(
  1. 我正在加载";get_pin.php";通过主页面的xmlHttpRequest("monitor.php"(
  2. "get_pin.php";具有查询$results=$myPDO->query("SELECT * FROM clients where id =".$user_id);使用这个查询,我获取被搜索姓名的人的id,然后获取该id的数据,创建一个geojson,这是get_pin.php的json编码结果。"geometry":{"type":"Point","coordinates":[143.3601,42.6500000000001]},"type":"Feature","properties":[]}

现在,我得到了,通过硬编码值,从id=1的客户端选择*。因此,即使我搜索不同的人的id,它也会在同一位置加载标记。

我试图解决的问题-"monitor.php";HTML

<tr>//table appears after the id is searched
<th>id</th>
<td><label id="lbl_id" name="lbl_id">'.$row["id"].'</label></td>
</tr>//further I also get other info of user in the same table

在同一页上-

function load_data(query, typehead_search = 'yes') {
$.ajax({
url: "dbconn.php",
method: "POST",
data: { query: query, typehead_search: typehead_search },
success: function (data) {
//show the table inside employee_data div
$('#employee_data').html(data);
//get the id and store it in js variable 
var l_id = document.getElementById('lbl_id').textContent;
alert(l_id);//I am getting the correct id
$.ajax({
type : "POST",
url  : "get_pin.php",
data : {l_id : l_id},
success: function(data){  
console.log(data);
},
error: function(err){
console.log(err);
}
});
}
});
}

在get_pin.php上,我正在获取数据

if (isset($_POST["l_id"])) {
require ("db_conn.php");  
$user_id =$_POST["l_id"];
try {             
$results=$myPDO->query("SELECT * FROM clients where id =".$user_id); 
/*get data convert it to a geojson*/

错误-ajax中的success函数为我提供了特定id的正确geojson输出。但是在我调用get_pin.php的xmlhttprequest中,响应是空白的。我得到了

Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at XMLHttpRequest.request.onload

如何将id的值从表传递到get_pin.php并在地图上获取该标记?

我得到了解决方案。我使用XMLHttpRequest来传递变量,而不是jQuery-ajax。

//this is to get and show the initial position of the user
var url = 'get_marker.php?id=';
map.on('load', function() {
var request = new XMLHttpRequest();
//I have added setInterval here to get updated value 
var clearIntervalValue = window.setInterval(function() {
var id = document.getElementById('l_id').textContent;
url = 'get_marker.php?id=';
url = url + id;
request.open('GET', url, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
console.log(this.response);
var json = JSON.parse(this.response);
map.getSource('drone').setData(json);
map.flyTo({
center: json.geometry.coordinates,
speed: 0.5
});
} else if (this.status == 404) {
clearInterval(clearIntervalValue);
}
};
request.send();
}, 2000);
//rest of the code...
});
<tr>
<th>id</th>
<td><label id="l_id" name="l_id">'.$row["id"].'</label></td>
</tr>

在get_marker.php 中

<?php
//check if the id is set
if (isset($_GET["id"])) 
{
//include database connection file
require ("db_conn.php");
$results=$myPDO->query("SELECT * FROM clients where id =".$_GET["id"]); 
}
?> 

最新更新