简体   繁体   中英

Using AJAX to reload part of a page from PHP

I have a webpage with a calendar that's created from PHP. I have a PHP function that creates the calendar (as a table) and returns it to the page to be inserted, like this:

<?php
    $calendar = new date("Y-m-d");
?>
<html>
    ...
    <?=$calendar?>
    ...
</html>

I have a Calendar.php file with a __toString() method that gets called when I do. That __toString() method is the method that creates the calendar

I know how to use AJAX to return the entire page but I'll like to just run the PHP function to recreate the calendar and send that to the page. Currently, we change the month by recreating it in the backend and refresh the whole page to show the new month. I don't like the refreshing so that's why I want to do AJAX (or really anything I can use to refresh a part of the page without reloading the whole page). How can I run that PHP code and send that to the page without reloading the page?

To clarify, on the page, I have a table with id="calendar". There are other things on the page but the main thing is, the calendar has arrows to navigate to the previous month and the next month. Currently, when you click on the arrows to either go to the next month or the previous month, the page is reloaded with the new month/date in the URL and our site gets the date from the query. I want to refresh the calendar with the new month using AJAX or any other way to execute the PHP code and send it to the browser, all without having to reload the entire page. I hope this all makes sense.

You can load the entire page using AJAX but its unnecessarily large amount of data.

You can just load the part you need: if there is a query string called 'calendar' or something you display only the calendar HTML. And you make a request to '?calendar' every minute or so.

This solution is not the best because you return plain HTML data. You could make an endpoint which returns JSON data with the calendar data and you parse it in JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM