I have an array but can't complete the final "success" step. I want to populate an html page with array data retrieved from a MySQL query triggered by POST data sent via JQuery Ajax. Console.log shows the array content being returned, but I don't know how to get it for the final step (populate HTML page).
Normally, I use PHP to generate an array and include the HTML page I want to display it on. I like the speed of Ajax, and that the data can be passed without a submit button, but I am stuck. I hope there's enough info below to identify my error(s).
Thanks for any assistance.
Here's my 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);
}
});
});
Here's the PHP page (display-agent-profile.html.php) to process the Query:
<?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();
}
?>