Jump to content

Where should I handle ajax calls?


Alpine418
 Share

Recommended Posts

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

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 

 

  • Like 4
  • Thanks 1
Link to comment
Share on other sites

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 ?

  • Like 2
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...