I have a php page and need to refresh part of it with AJAX.
function reloadChart(number) {
console.log("Reloading chart with number:", number);
var xmlhttp = new XMLHttpRequest();
var url = "index.php?r=b3-data/chart_data2&number=" + number;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
........
<div class="chart-container" id="chartContainer">
<?php include('chart_data2.php');?>
</div>
<div style="text-align: center;">
<button id="nextButton"><< Next</button>
<button id="previousButton">Previous >></button>
</div>
chart_data2.php is working properly with direct request through browser. But AJAX call with Previous and Next buttons does not refresh the chart of main page.
Brower console is displaying "Reloading chart with number:1" but chart_data2.php does not getting number through GET
PHP is interpreted when you first load the page, so you cannot simply "reload some part of it". What you could do, is fetch the updated html from the server using an ajax request, and then replace the innerHTML of your chartContainer
with this new HTML.
The following example uses fetch
, which is a modren implementation of XmlHttpRequests. I highly suggest using it, since it's way easier to use and available in vanilla Javascript.
async function reloadChart(number) {
console.log("Reloading chart with number:", number);
const response = await fetch( "index.php?r=b3-data/chart_data2&number=" + number);
const newChartHtml = response.text();
document.getElementById('chartContainer').innerHTML = newChartHtml
}
You havn't posted any information about the backend side of thing, or how you are using the route to refresh your chart data, so I cannot speculate on how to handle the backend side of things. But, this implementation assume that the index.php?r=b3-data/chart_data2...
will ONLY return the HTML of the chart_data2.php
, since this is the only part we want to refresh.