Я пытаюсь изучить PHP/Ajax и застреваю. Я пытаюсь получить результат моего запроса AJAX для рендеринга в элементе div, объявленном вне моего класса PHP.
У меня есть файл PHP с одним классом с именем dashboard
, который обрабатывает запросы к базе данных после получения переменной post из запроса ajax, который выглядит следующим образом.
public function loadTeamMembersChart($teamID, $lecturer_id, $teamColour){
$db = $this -> db;
if (!empty ($teamID) && !empty ($lecturer_id)){
$result = $db -> loadTeamMembersChart($teamID, $lecturer_id);
if ($result) {
$response["teamMember"] = $result;
$teamMembers = $_SESSION["teamMember"] = $result;
//Pass the results to the below function
loadTeamMembers($teamMembers, $teamColour);
} else {
$response["result"] = "failure";
$response["message"] = "Unable to Find Team Member Data";
return json_encode($response);
}
} else {
return $this -> getMsgParamNotEmpty();
}
}
Затем в том же файле php у меня есть глобальная функция, в которую передаются результаты, называемая loadTeamMembers, как показано ниже.
function loadTeamMembers($teamMembers, $teamColour){
//start to break up the teamMember object and store in variables
$teamMemberName = $_SESSION['teamMember']['all_team_member_names'];
$teamMemberPoints = $_SESSION['teamMember']['all_team_member_points'];
$teamMemberStudentNumber = $_SESSION['teamMember']['all_team_member_studentNumbers'];
$teamMemberLastActive = $_SESSION['teamMember']['all_date_last_present'];
$teamMemberTeamID = $_SESSION['teamMember']['all_team_ids'];
// The `$teamMemberData` array holds the chart attributes and data for the team object
$teamMemberData = array(
"chart" => array(
"caption" => "Student Team-Member Progress Chart",
"xAxisname"=> "Team-Member Name",
"yAxisName"=> "Points",
//Configure no.of visible plots
"numVisiblePlot"=> "5",
"theme"=> "zune",
"exportenabled"=> "1",
"exportMode"=> "server"
),
"categories" => array(
"category" => array()),
"dataset" => array(
"data" => array())
);
$teamMemberCount = 0;
// Push the data into the array
if (is_array($teamMemberName) || is_object($teamMemberName))
{
foreach($teamMemberName as $key => $value){
array_push($teamMemberData["categories"]["category"], array(
"label" => $teamMemberName[$teamMemberCount]." ".$teamMemberStudentNumber[$teamMemberCount]." Profile was last active on ".$teamMemberLastActive[$teamMemberCount]));
array_push($teamMemberData["dataset"]["data"], array(
"value" => $teamMemberPoints[$teamMemberCount],
"color"=> $teamColour));
$teamMemberCount++;
}
}
//encode the built team-member array so that it is returned to the ajax success request
echo $jsonEncodedTeamMemberData = json_encode($teamMemberData);
}
Затем в том же файле, но вне обоих классов PHP, у меня есть следующий скрипт внутри моего HTML:
<script>
function getTeamMembers(teamID,lecturer_id, teamColourCode){
//Variables needed to query the external DB to return required data to populate the charts
var teamInfo = {
"teamID" : teamID,
"lecturer_id" : lecturer_id,
"teamColourCode" : teamColourCode
};
/*
The below is used for the 'was a student present for the most recent quiz' pie chart. A boolean is set so that the post request knows
that we only need to call the loadIfTeamMemberWasPresent(); function, as the data was already obtained in the first ajax request. However, we don't want
to use that data on the first ajax call.
*/
var teamDetails = {
"teamClicked" : true
};
//Below is the first ajax call
$.ajax({
data: teamInfo,
url: 'dashboard.php',
type: 'POST',
success : function(data) {
console.log(data)
chartData = data;
apiChart = new FusionCharts({
type: 'scrollColumn2d',
renderAt: 'team-member-chart-container',
width: '550',
height: '350',
dataFormat: 'json',
dataSource: data
});
apiChart.render();
},
//Once the first ajax call has completed, we can then call the second ajax request to populate the pie-chart graph
complete:function(){
$.ajax({
data: teamDetails,
url: 'dashboard.php',
type: 'POST',
success : function(data) {
console.log(data)
chartData = data;
apiChart = new FusionCharts({
type: 'pie2D',
renderAt: 'teamMember-present-container',
width: '550',
height: '350',
dataFormat: 'json',
dataSource: data
});
apiChart.render();
},
});
}
});
}
</script>
Однако там, где я написал $columnChartTeamMember =...
, я не могу получить доступ и отобразить свою диаграмму в идентификаторе div с именем team-member-chart-container
.
Если возможно, я стараюсь не иметь HTML в самом классе, поскольку другие диаграммы из других классов также должны отображаться в других идентификаторах div, таких как individual-student-container
.
Я попытался прочитать руководство PHP Simple HTML DOM Parser, которое можно найти здесь, но как новичок, это оставляет меня немного в замешательстве. Я также не уверен, что это то, что мне нужно.
Я основывал свой подход на официальной документации, предоставленной fusioncharts, которую можно найти здесь.
Если кто-нибудь может предложить какое-то руководство о том, как я могу отобразить свою диаграмму в упомянутом div-id, я был бы очень признателен.
ИЗМЕНИТЬ
В конце концов, мне удалось решить мою проблему, вернув полученные данные из моего PHP-скрипта обратно в запрос AJAX, а затем построив свои диаграммы из вызова success
запроса ajax. Я обновил свой код, чтобы показать, как это было достигнуто. Я пропустил обработку второго запроса ajax, так как данные уже были получены при первом вызове. Однако я пока не хотел его извлекать, поэтому я сделал второй запрос, как только первый был завершен. Теперь все работает отлично.
<div>
прямо из PHP, вам нужно вводить ее через JS. - person Anuga   schedule 25.07.2018FusionCharts
? - person abc   schedule 25.07.2018