Alpine418 Posted January 20, 2023 Share Posted January 20, 2023 Hi, I've a few ajax calls from the frontend, which I handle in the _init.php file in the template folder. The response is always json. The code works, but is there a "better" place for such code than in the _init.php? The functionality on my enviroment is some kind of signature/login validation which should be called on every page, idenified by a query param (e.g. /example/path?foo=1). Dummy example: if (input()->get('foo')) { // do foo and response json $foo = [ 'foo' => 'bar' ]; header('Content-Type: application/json; charset=utf-8'); echo json_encode($foo); exit; } if (input()->get('bar')) { // do bar and response json $bar = [ 'foo' => 'bar' ]; header('Content-Type: application/json; charset=utf-8'); echo json_encode($bar); exit; } Thanks. Link to comment Share on other sites More sharing options...
gs-df Posted January 20, 2023 Share Posted January 20, 2023 I saw differnt ways to handle ajax calls. I use 2. and 3.(for more complex projects) 1. Ajax folder with php files for each request, which include processwire index.php 2. URL-Hooks https://processwire.com/blog/posts/pw-3.0.173/#new-type-of-hook-for-handling-request-urls 3. AppAPI Module https://processwire.com/modules/app-api/ (Uses URL-Hooks or pageNotFound-Hook) 4. ajax.php template file https://github.com/kreativan/wirekit-core/blob/main/site-wirekit-core/templates/ajax.php 5. ajax request logic in each template file 4 1 Link to comment Share on other sites More sharing options...
Alpine418 Posted January 20, 2023 Author Share Posted January 20, 2023 Thank you! URL hooks looks like the easiest way without overhead for a a few API calls. Did PW offer any solution for POST request with JSON body? Or do I need to use native PHP functions? Link to comment Share on other sites More sharing options...
gs-df Posted January 20, 2023 Share Posted January 20, 2023 $input->post provides access to your POST variables https://processwire.com/docs/start/variables/input/ Link to comment Share on other sites More sharing options...
Alpine418 Posted January 20, 2023 Author Share Posted January 20, 2023 Yes, but $input->post helps only when the data got send as FormData. But you can post data also as json in the body of request (fewer code in JavaScript). Native PHP example for reading them: // Takes raw data from the request $json = file_get_contents('php://input'); // Converts it into a PHP object $data = json_decode($json); Looks like PW has no functions. So I will use the native solutions from PHP. No problem ? 2 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now