Jump to content

Best practice for ajax requests (where to put the ajax templates)


Stefanowitsch
 Share

Recommended Posts

Hello! 

I want to make use of a JS modal that contains a form. Then the user submits the form I want to handle the submission via ajax and display a "success" message within the modal. 

I am wondering what is the best practice to handle ajax calls within processwire in general?

Usually I would create a static PHP file that handles all the form validation which is then called via ajax after pressing the "submit" button.

My question is: Where do I place such a static file within the PW folder structure?

I want to create a custom "ajax" folder and place that file there:

image.png.79a86ed2cb4ec74cd92ec5c586714093.png

Then make the ajax request. This is a JS file that handles all functions for the site and sits somewhere within the "scripts" folder.

$.ajax({
  type: "POST",
  url: "/site/templates/ajax/form-submit.php",
  data: formData
}).done(function (data) {
  console.log('form submitted');
  console.log(data);
});

This call results in a 403 (forbidden) error. The URL that is called looks like that:

https://mywebsite/site/templates/ajax/form-submit.php

So my question is: Do I need to create a custom template file (=form-submit) within the processwire backend first and then create a page with that template to make it accessible through an ajax request? 

Link to comment
Share on other sites

Hi @Stefanowitsch,

Very quick response.

There is no best practice really.

9 minutes ago, Stefanowitsch said:

This call results in a 403 (forbidden) error. 

ProcessWire is blocking access to form-submit.php because it is not a template file.

There are different approaches to handling ajax requests, including:

  1. Creating a dedicated page (it doesn't have to be visible) and calling that
  2. Home page to handle all requests. You can then include your form-submit.php and let it deal with the response and send it back to your home template.
  3. Same page the form was called in (1-3 are similar).
  4. Using the new URL Hooks.
Edited by kongondo
  • 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...