1

I am creating a module that exposes a form for customers to fill in. Upon submission, an ajax request request is made to a PHP script which calls the API.

Now I have already tested this in a separate simple site consisting of just an HTML page (with the form and Javascript) and a PHP file with the function.

As I'm still learning module development in Magento, I'd like to know where my PHP function should go and how to call it (What would be the URL to call)? My first guess is that I need to create a controller with a custom method.

Anyway, here is my PHP function and corresponding Javascript:

Thank you

submit.php

<?php

function is_ajax() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function subscribe() {
  if (is_ajax()) {
    $fieldData = array(
      'api_key'    => '99999999999',
      'email'      => $_POST['email'],
      'properties' => json_encode(array(
        '$first_name' => $_POST['firstname'],
        '$last_name' => $_POST['lastname']
      ))
    );

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,"https://somesite.com/api/v1/subscribe");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldData);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $server_output = curl_exec ($ch);

    curl_close ($ch);

    echo $server_output;
    // echo json_encode($server_output);
    // echo json_encode($fieldData);
  }
}

?>

_index.js

$(document).ready(function() {
  $('#testform').submit(function(event) {
    var formData = {
      'email'     : $('input#email').val(),
      'firstname' : $('input#firstname').val(),
      'lastname'  : $('input#lastname').val(),
    };
    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: 'submit.php/subscribe',
      data: formData,
      encode: true,
      success: function(data) {
        $('#result').html(JSON.stringify(data));
      },
      error: function(XHR, textStatus, errorThrown) {
        console.log(errorThrown);
      }
    });
    event.preventDefault();
  });
});
3
+100

Yes you need a small module for that.

First create app/etc/modules/Vendor_Module.xml with the following content:

<?xml version="1.0"?>
<config>
    <modules>
        <Vendor_Module>
            <active>true</active>
            <codePool>local</codePool>
        </Vendor_Module>
    </modules>
</config>

Then create app/code/local/Vendor/Module/etc/config.xml :

<?xml version="1.0"?>
<config>
    <modules>
        <Vendor_Module>
            <version>0.0.1</version>
        </Vendor_Module>
    </modules>

    <frontend>
        <routers>
            <module>
                <use>standard</use>
                <args>
                    <module>Vendor_Module</module>
                    <frontName>module</frontName>
                </args>
            </module>
        </routers>
        <layout>
            <updates>
                <module>
                    <file>vendor/module.xml</file>
                </module>
            </updates>
        </layout>
    </frontend>
</config>

Now let's create the controller in app/code/local/Vendor/Module/controllers/IndexController.php :

<?php

class Vendor_Module_IndexController extends Mage_Core_Controller_Front_Action {

    public function indexAction()
    {       
        $this->loadLayout(); 

        $this->renderLayout();
    }

    public function submitAction()
    {
        if (_isAjax()) {
            $fieldData = array(
                'api_key'    => '99999999999',
                'email'      => $this->getRequest()->getPost('email'),
                'properties' => Mage::helper('core')->jsonEncode(array(
                    '$first_name' => $this->getRequest()->getPost('firstname'),
                    '$last_name' => $this->getRequest()->getPost(''lastname')
                ))
            );

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL,"https://somesite.com/api/v1/subscribe");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldData);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $server_output = curl_exec ($ch);

            curl_close ($ch);

            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($server_output));
        }
    }

    protected function _isAjax() 
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }
}

Now you need to create the template that will contain your form and your JS.

First you need to create app/design/frontend/base/default/layout/vendor/module.xml with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
    <module_index_index>
        <reference name="content">
            <block type="core/template" name="customform" template="vendor/module/form.phtml" />
        </reference>
    </module_index_index>
</layout>

And then you can create your template under app/design/frontend/base/default/template/vendor/module/form.phtml.

In this file you'll need to add your form code as well as the following modified JS:

$(document).ready(function() {
  $('#testform').submit(function(event) {
    var formData = {
      'email'     : $('input#email').val(),
      'firstname' : $('input#firstname').val(),
      'lastname'  : $('input#lastname').val(),
    };
    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: '/module/index/submit',
      data: formData,
      encode: true,
      success: function(data) {
        $('#result').html(JSON.stringify(data));
      },
      error: function(XHR, textStatus, errorThrown) {
        console.log(errorThrown);
      }
    });
    event.preventDefault();
  });
});

Important note: your form will be accessible by calling http://yourmagentostore.com/module/index/index or simply http://yourmagentostore.com/module

  • Wow! Thanks Raphael. Please allow me a few a minutes to test this out quick – maGz Jul 7 '16 at 12:53
  • Amazing! Works beautifully. Got the response I was hoping for: "{\"person\": {\"object\": \"person\", \"id\": null, \"email\": \"doe@test.com\"}, \"already_member\": false, \"list\": {\"updated\": \"2016-06-02 10:38:04\", \"person_count\": 2, \"name\": \"Newsletter\", \"created\": \"2016-06-02 10:38:04\", \"list_type\": \"list\", \"id\": \"98744\"}, \"email\": \"doe@test.com\"}" – maGz Jul 7 '16 at 13:41
  • @maGz glad it worked. Feel free to mark your question as answered so it'll benefit for others – Raphael at Digital Pianism Jul 7 '16 at 13:46
  • And obviously, if I'm just showing this as a block I can just create a reference to it in my local.xml as: <reference name="footer"> <block type="core/template" name="customform" template="vendor/module/form.phtml" /> </reference> and then in app/design/frontend/package/default/template/page/html/footer.phtml, call it as $this->getChildHtml('customform'); ... correct? – maGz Jul 7 '16 at 13:48
  • 100 points all yours bud. I've definitely now also learned something for the future :) – maGz Jul 7 '16 at 13:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.