Jump to content

Saving $_POST data to a new page


a-ok
 Share

Recommended Posts

Hi folks,

Okay this is a bit of an odd one to explain so if you need to email please do at rich.g.cook(at)gmail.com and I'll happily pay a fee for any solutions if needed.

I'm building a simple cart/checkout setup and on submission at the checkout the form action, on a static test, was submission.php and on this .php file it got the $_POST data from the form, parsed it using twig, and items and pushed it using swift mail to the seller and the buyer.

This all works fine statically, but the issue is now it's on a CMS the $_POST data isn't getting saved across so upon submission all the fields (first name, address etc) are just returning blank.

If I hard link the form submission to the templates folder to submission.php then it works but in the URL you have the weird .php whereas if I add it as a page and template in the CMS it drops the .php which is nicer but it doesn't seem to save any of the data this way.

I know this is a bit confusing, but hopefully I've made some sense and you guys could help.

Thanks,

R

Link to comment
Share on other sites

Hi Richard - this should all be very easy to solve.

You say that linking directly to submission.php in the templates folder works - that is weird, because the htaccess rules that come with PW prevent calling php files from the templates folder directly :) You should get a forbidden error. If you want to call the file directly, you should place it in a folder outside the site folder. This is pretty common practice when processing forms, or calling ajax scripts. You can redirect ($session->redirect) back to a page after the submission, so the user won't even see the .php file in their browser.

That said, there should also be no problem processing a form from a page that has the submission.php template if you'd prefer. I think we need to see your code so we can help - should be an easy fix! 

Link to comment
Share on other sites

Hi @adrian,

Many thanks for the reply, and the encouragement!

Yep, linking directly to the submission.php file works, but only if I remove the htaccess rules ;) I did so as a test to make sure that worked... but of course changed back. I do get a forbidden error if I add the rules back in.

Okay, below is my submission.php file... you can see generally what it is doing. Taking the $_POST data, storing them, then passing them into a few email templates, sending those on, and then echo'ing out an order summary (order-summary.php) page.

<?php

require_once 'ecommerce/swiftmailer/lib/swift_required.php';
require_once 'ecommerce/twig/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('./');

$twig = new Twig_Environment($loader, array(
'cache' => 'cache/',
));

$twig->clearCacheFiles();

$data['firstname'] = $_POST['firstname'];
$data['lastname'] = $_POST['lastname'];
$data['email'] = $_POST['email'];
$data['telephone'] = $_POST['telephone'];
$data['street0'] = $_POST['street0'];
$data['street1'] = $_POST['street1'];
$data['street2'] = $_POST['street2'];
$data['city'] = $_POST['city'];
$data['state'] = $_POST['state'];
$data['zip'] = $_POST['zip'];
$data['countrycode'] = $_POST['countrycode'];

if (isset($_POST['shipping'])) {
$data['shipping']             = $_POST['shipping'];
$data['shipping_firstname']   = $_POST['shipping_firstname'];
$data['shipping_lastname']    = $_POST['shipping_lastname'];
$data['shipping_email']       = $_POST['shipping_email'];
$data['shipping_telephone']   = $_POST['shipping_telephone'];
$data['shipping_street0']     = $_POST['shipping_street0'];
$data['shipping_street1']     = $_POST['shipping_street1'];
$data['shipping_street2']     = $_POST['shipping_street2'];
$data['shipping_city']        = $_POST['shipping_city'];
$data['shipping_state']       = $_POST['shipping_state'];
$data['shipping_zip']         = $_POST['shipping_zip'];
$data['shipping_countrycode'] = $_POST['shipping_countrycode'];
}

//Check the prices againts you DD
$products = (array) json_decode($_POST['cart']);

// Check this against your DB and get the correct discount
$discount = $_POST['discount'];
$discount_amount = $discount == 'TEST123' ? 50 : 0;

// Check the shipping price
$shipping_price = 0;

foreach ($products as $value)
{
if (property_exists($value, 'size'))
{
if ($value->size > $shipping_price)
{
$shipping_price = $value->size;
}
}
}

switch($shipping_price)
{
case 1:
$shipping_price = 5;
break;
case 2:
$shipping_price = 10;
break;
case 3:
$shipping_price = 15;
break;
};

$total = 0;

foreach ($products as $product)
{
$total += $product->price; 
}

$total -= $discount_amount;

$total += $shipping_price;

$body = $twig->render('order-email.php', array(
'data'            => $data,
'products'        => $products,
'discount_amount' => $discount_amount,
'shipping_price'  => $shipping_price,
'total'           => $total
));

$summary = $twig->render('order-summary.php', array(
'data'            => $data,
'products'        => $products,
'discount_amount' => $discount_amount,
'shipping_price'  => $shipping_price,
'total'           => $total
));

// Show confirmation/summary template
echo $summary;

//$transport = Swift_MailTransport::newInstance();
$transport = Swift_SmtpTransport::newInstance('tls://smtp.gmail.com', 465)
  ->setUsername('rich.g.cook@gmail.com')
  ->setPassword('_______'); // Removed for example

$mailer = Swift_Mailer::newInstance($transport);

$seller_email = Swift_Message::newInstance()
->setSubject('Invoice - Admin')
->setFrom(array('rich@rdck.co' => 'Admin')) // To change
->setTo(array('rich.g.cook@gmail.com' => 'You')) // To change
->setBody($body, 'text/html');

$customer_email = Swift_Message::newInstance()
->setSubject('Invoice - Customer')
->setFrom(array('rich@rdck.co' => 'Admin')) // To change
->setTo(array($_POST['email'] => 'Customer'))
->setBody($body, 'text/html');

$mailer->send($seller_email);
$mailer->send($customer_email);
Link to comment
Share on other sites

Yep, linking directly to the submission.php file works, but only if I remove the htaccess rules  ;) I did so as a test to make sure that worked... but of course changed back. I do get a forbidden error if I add the rules back in.
 
Ok - that makes sense - you had me confused there for a minute :)
 
Firstly, it's not important, but the PW way of handling post data is to use: $input->post->firstname etc.
 
Secondly, teppo has a great SwiftMailer module for PW - works great unless you need to get into batch sending and want access to the throttler and decoration plugins etc. You should try that instead of calling swift manually.
 
 
Now onto the problem at hand - I am not sure at this point :)
 
Do you have debug mode turned on so you are seeing all PHP errors?
I am wondering if those require_once paths are correct - is the ecommerce folder inside your templates directory?
Have you tried just directly echoing out $_POST['firstname'] with nothing else in the template file? 
Can the page return any content at all, like: echo 'test'; ?
 
 
 
 
 
 
 
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.
  • Similar Content

    • By Juergen
      Hello @ all
      I want to share a new module with you, which makes the creation and validation of forms easy.  Take a look at the following example of a simple contact form:
      // A very simple example of a contactform for demonstration purposes $form = new Form('contactform'); $gender = new Select('gender'); $gender->setLabel('Gender'); $gender->addOption('Mister', '0'); $gender->addOption('Miss', '1'); $form->add($gender); $surname = new InputText('surname'); $surname->setLabel('Surname'); $surname->setRule('required'); $form->add($surname); $name = new InputText('name'); $name->setLabel('Name'); $name->setRule('required'); $form->add($name); $email = new InputText('email'); $email->setLabel('E-Mail'); $email->setRule('required'); $form->add($email); $subject = new InputText('subject'); $subject->setLabel('Subject'); $subject->setRule('required'); $form->add($subject); $message = new Textarea('message'); $message->setLabel('Message'); $message->setRule('required'); $form->add($message); $privacy = new InputCheckbox('privacy'); $privacy->setLabel('I accept the privacy policy'); $privacy->setRule('required')->setCustomMessage('You have to accept our privacy policy'); $form->add($privacy); $button = new Button('submit'); $button->setAttribute('value', 'Send'); $form->add($button); if($form->isValid()){ print_r($form->getValues()); // do what you want } // render the form echo $form->render(); This piece of code creates a simple contact form and validates it according to the validation rules set. Inside the isValid() method you can run your code (fe sending an email)
      Highlights:
      30+ validation types Support for UiKit 3 and Bootstrap 5 CSS framework SPAM protection Highly customizable Hookable methods for further customization Multi-language You can download and find really extensive information on how to use at https://github.com/juergenweb/FrontendForms.
      Please report errors or suggestions directly in GitHub.
      Best regards and happy testing 🙂
    • By Vineet Sawant
      Hi,
      I'm trying to import some heavy data into Processwire, but I'm not sure what would be the best way to do it.
      Usually I use CSV to Pages plugin, but this time the data is too heavy(~40k rows with 10+ columns of excel sheet), thus this plugin can't help.
      I also tried Tasker plugin but I can't seem to go through the setup itself, it requires some template setup but I'm totally clueless about how to do it, so that plugin is not of any use either.
      I wanted to know from you guys how you do it and in future what would be the best way to migrate thousands of rows of data in to PW.
       
      Thanks.
       
       
    • By 997 998 999
      Hello,
      I'm trying to edit the field of a page with a value from a javascript fetch post request but I can't get the
      file_get_contents("php://input") or
      $_POST value in my PHP file.
      I created a `update` template and a `update` page (to allow access from fetch request and avoid 404/403/... errors) containing this code :
      $data = file_get_contents('php://input'); echo $data; # test edit the page field with random value #$home = $pages->get("/"); #$home->of(false); #$home->testfield = "test value"; #$home->save(); # test fetch response with random value #echo "test fetch response"; That I fetch request with my client javascript like this :
      fetch('/update', { method: 'POST', body: 'test' }) .then(function(response) { return response.text(); }) .then(function(data) { console.log(data); }) .catch(error => console.log('error')) } The field edit works fine and I get the test response from the `update` file but I can't get the posted value, I only get `<empty string>`. It is working fine outside of ProcessWire so I guess this is related to how PW handle $_POST ?
      I found this post where it seems to be working :
       
      Is there any way to get post value from javascript fetch request? What am I doing wrong?
       
      Thank you
       
       
       
    • By benbyf
      Hi, Looking to create form elements on a page–some input with a colection of form inputs and the appropriate labels and variables for that input. I've used ProForms in the past and rolled out my own when creating simply one off forms, but I wonder if anyone has found a good way of allowing form creation on page editing so that clients can adhocly make and edit forms?
      Thanks
    • By dimitrios
      Hello,
      this module can publish content of a Processwire page on a Facebook page, triggered by saving the Processwire page.
      To set it up, configure the module with a Facebook app ID, secret and a Page ID. Following is additional configuration on Facebook for developers:
      Minimum Required Facebook App configuration:
      on Settings -> Basics, provide the App Domains, provide the Site URL, on Settings -> Advanced, set the API version (has been tested up to v3.3), add Product: Facebook Login, on Facebook Login -> Settings, set Client OAuth Login: Yes, set Web OAuth Login: Yes, set Enforce HTTPS: Yes, add "https://www.example.com/processwire/page/" to field Valid OAuth Redirect URIs. This module is configurable as follows:
      Templates: posts can take place only for pages with the defined templates. On/Off switch: specify a checkbox field that will not allow the post if checked. Specify a message and/or an image for the post.
      Usage
      edit the desired PW page and save; it will post right after the initial Facebook log in and permission granting. After that, an access token is kept.
       
      Download
      PW module directory: http://modules.processwire.com/modules/auto-fb-post/ Github: https://github.com/kastrind/AutoFbPost   Note: Facebook SDK for PHP is utilized.


×
×
  • Create New...