我有一个阵列但无法完成最后的“成功”步骤。我想填充一个html页面,其中包含从通过JQuery Ajax发送的POST数据触发的MySQL查询中检索到的数组数据。 Console.log显示了返回的数组内容,但我不知道如何在最后一步获取它(填充HTML页面)。
通常,我使用PHP生成一个数组并包含我想要显示它的HTML页面。我喜欢Ajax的速度,并且数据可以在没有提交按钮的情况下传递,但我被卡住了。我希望下面有足够的信息来确定我的错误。
感谢您的帮助。
这是我的Ajax:
// Get value of drop-down selection
$( "#agent_preview" ).change(function(){
var broker_agent_id = $( this ).val();
console.log(broker_agent_id);
$.ajax({
url: '../ajax/display-agent-profile.php',
type: 'POST',
data: { broker_agent_id: broker_agent_id },
cache: false,
success: function(data){
$("#preview").html(data);
}
});
});
这是处理查询的PHP页面(display-agent-profile.html.php):
<?php
if(isset($_POST['broker_agent_id'])){
// Receive value of variable from ajax script @script.js and store in variable
$broker_agent_id = htmlspecialchars($_POST['broker_agent_id']);
// Connect to database
include '../brokers/includes/dbconnect.php';
// Get broker_id of agent using broker_agents.id
try {
$sql = "SELECT broker_id FROM broker_agents
WHERE id = :id";
$s = $db->prepare($sql);
$s->bindValue(':id', $broker_agent_id);
$s->execute();
// Store query results in array
$result = $s->fetch(PDO::FETCH_ASSOC);
// Store broker id in variable
$broker_id = $result['broker_id'];
}
catch (PDOException $e) {
$errMsg = "Error fetching broker id from database " . $e->getMessage();
include 'includes/error.html.php';
exit();
}
// Retrieve data for agent based on broker_agents.broker_id and brokers.id (brokers.id = broker_agents.broker_id)
try {
$sql = "SELECT brokers.id, broker_agents.profile_photo, broker_agents.first_name, broker_agents.last_name, brokers.company_logo, brokers.company_name, brokers.address1, brokers.address2,
brokers.telephone, broker_agents.cell, broker_agents.agent_email, brokers.website, brokers.company_bio, broker_agents.about_me, brokers.services, broker_agents.affiliations,
broker_agents.states_served, broker_agents.counties_served
FROM brokers
INNER JOIN broker_agents
ON brokers.id = broker_agents.broker_id
WHERE broker_agents.id = :id
AND broker_agents.broker_id = :broker_id";
$s = $db->prepare($sql);
$s->bindValue(':id', $broker_agent_id);
$s->bindValue(':broker_id', $broker_id);
$s->execute();
// Store agent results in associative array
$agent = $s->fetch(PDO::FETCH_ASSOC);
}
catch (PDOException $e) {
$errMsg = "Error fetching agent data from database " . $e->getMessage();
include 'includes/error.html.php';
exit();
}
// Disconnect
$db = NULL;
include 'profile-preview.html.php';
exit();
}
?>