Ad

OctoberCMS Using Ajax API With No-script Fallback In Page Php Section

- 1 answer

My current base for a simple contact form is:

A page containing the form and the form validation in the php section with a native function like so:

function onStart(){if(Request::isMethod('post')) /* do stuff */}

Above is my "no-script" solution.

Now, when I want to enable OctoberCMS' Javascript API I have to call a self defined function in the php section, for example:

function onSubmit(){/* do stuff */}

How could I combine both in one function so that /* do stuff */ triggers, regardless if the request was send via Ajax or pure php?

Ad

Answer

I found the answer.

OctoberCMS provides a native method to let a form trigger a custom onMyfunction(), just by using another way of implementing the form.

For anybody who might get into the same problem, here's the code:

<?php
function onMyfunction(){}
?>
==
<html>
{{ form_open({ request: 'onMyfunction', id: 'my-form' }) }}
</html>

This will send the post data to the php handler, regardless if Javascript is enabled or not. Now you only need to initiate your Ajax API with:

<script>
$('#my-form').submit(function(evt){
    evt.preventDefault();
    $(this).request('onMyfunction',{})
});
</script>
Ad
source: stackoverflow.com
Ad