AJAX
To add ajax functional into MV, you need to follow the next steps.
1. Pass the full path to project into JavaScript (add a line with the path into "views/main-header.php" file). This variable will keep your actual root path to be available on local and production servers.
<script type="text/javascript"> var rootPath = "<? echo $mv -> root_path; ?>"; </script>
2. In "views" folder create a new folder (name it "ajax" or other) for the files that will be called with ajax. Put ".htaccess" file into this folder with an option of "RewriteEngine off" in order to block Apache Mod Rewrite. In new version of MV this folder is already created.
4. Create php file, that will accept ajax requests, for example "request.php".
5. In JavaScript file add a code to send ajax requests.
var params = "a=1&b=2"; $.ajax( { type: "POST", dataType: "html", url: rootPath + "views/ajax/request.php", data: params, success: function(data) { //Response data processing } });
6. In "views/ajax/request.php" file write the following code.
<? include "../../config/autoload.php"; $mv = new Builder(); if(isset($_POST["a"], $_POST["b"])) { //Process the query ... //Send HTTP headers if needed and query result header("Content-type: text/html"); echo $mv -> products -> display(); } ?>
7. Now you have a ready construction to send ajax request from browser to server, generate server response and process the final result in JavaScript.
Previous section
Work with sessions