I have an HTML form with method = "POST" and a submit button. Within my file 'purchases.controller.php', if I do a var_dump ($_POST), you can see all my POST variables belonging to the inputs of the form correctly.
Now, I have another file called 'aux.php' which gets an array by AJAX and then I pass it to a function of a class in the file 'purchases.controller.php'. There, I want to manipulate the array and the POST variables that are arriving, but it only allows me to manipulate the array, the POST within the function do not exist.
Does anyone know what I'm doing wrong?
I share the purchases.controller.php code:
//HERE SHOWS ME THE POST VARIABLES AS THE 'registroUsuario', ETC.
var_dump($_POST)
class Purchases {
public function ctrCash(&$completeArray){
//THE ARRAY IS SHOWN CORRECTLY
var_dump($completeArray);
if(isset($_POST["registroUsuario"])){
if(preg_match('/^[a-zA-ZñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["registroUsuario"]) &&
preg_match('/^([0-2][0-9]|3[0-1])(\/|-)(0[1-9]|1[0-2])\2(\d{4})$/', $_POST["registroCalendario"]) &&
preg_match('/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/', $_POST["registroEmail"]) &&
preg_match('/^(?:\D*\d){2,4}\D*$/', $_POST["registroDireccion"]) &&
preg_match('/^[0-9]{7,12}$/', $_POST["registroTelefono"])) {
//HERE I WANT TO MANIPULATE EVERYTHING, BUT I CAN NOT SINCE THEY ARE NOT ARRIVING THE POST
}
And here is the file aux.php:
if(isset($_POST['completeArray'])){
include ('purchases.controller.php');
$completeArray = json_decode($_POST['completeArray'], true);
$newPurchase = new Purchase();
$newPurchase -> ctrCash($completeArray);
}
Related
I am using a Toolset plugin for Wordpress and try to make it save the id of the page where the user fills up the form.
This plugin has "hooks" for it.
This is what they say about it.
cred_save_data
Description
This hook allows doing a custom action when post data is saved to the database.
Arguments
post_id. The id of the current created or edited post.
form_data. An associative array of data about current form:
id. The form of ID.
post_type. The post type that the form operates on.
form_type. The type of form - 'new' or 'edit'.
container_id. Refers to the post_id of the post, page or custom post type that contains the CRED form
EXAMPLE:
add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
// if a specific form
if ($form_data['id']==12)
{
if (isset($_POST['my_custom_field']))
{
// add it to saved post meta
add_post_meta($post_id, '__my_custom_field', $_POST['my_custom_field'], true);
}
}
}
so I added this modified PHP code in functions.php of the theme:
add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
// if a specific form
if ($form_data['id']==2080) // the id of the form
{
if (isset($_POST['container_id']))
{
// add it to saved post meta
add_post_meta($post_id, 'formetadata', $_POST['container_id'], true);
}
}
}
where for metadata is a slug for custom field created to collect metadata, including the id of the page, where the form was filled up.
It does not work. The form collects data, creates a post, but the field for metadata remains empty.
What did I do wrong?
I don't have enough knowledge about PHP and may be completely misunderstood instructions...
So looking at the docs and your function I see they use the key container_id and you use $_POST['container_id']. Im just guessing but it sounds like those are the same id? If so then you can access it via the $form_data like below:
add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
// if a specific form
if ($form_data['id']==2080) // the id of the form
{
if (isset($_POST['container_id']))
{
// add it to saved post meta
add_post_meta($post_id, 'formetadata', $form_data['container_id'], true);
}
}
}
I have a function that processes sales via a third-party service, processes the result and returns an array with the Status "Success" or "Invalid." This sales call is made using the gform_after_submission hook applied to the specific form.
What I need to do is store the "Success" or "Invalid" result in the array as a variable that I can later pass to a function to validate or invalidate the credit card field, using gform_validation hook.
I'm declaring the variable in a function, like so:
function foo {
...code to sell product through API...
$status = $checkoutShoppingCartRequest['Result']['Status'];
}
When I print the variable $status within the function, it is showing either Success or Invalid like it should.
Here is other function where I need to use this variable, passed to gform_validation, which fails every time regardless of Success or Invalid result:
function MBvalidate( $validation_result ) {
$form = $validation_result['form'];
if ( $status !== "Success") {
$validation_result['is_valid'] = false;
foreach( $form['fields'] as &$field ) {
if ( $field->id == '34' ) {
$field->failed_validation = true;
$field->validation_message = 'Your credit card could not be processed.';
break;
}
}
}
//Assign modified $form object back to the validation result
$validation_result['form'] = $form;
return $validation_result;
}
add_filter( 'gform_validation_47', 'MBvalidate' );
I have tried passing the variable a number of different ways, via globals and sessions, etc.
I am new to GF development so I am sure I'm missing something. I'd appreciate any direction.
The gform_after_submission action hook runs after gform_validation.
Anyway, assuming you can find a hook that runs earlier, what I would do is store a unique variable for each submitted form using the Transients API's set_transient() and get_transient() functions. For example you can create a hidden field in every form which you populate with a random ID. Use this random ID as a key to store and retrieve the Success/Invalid result.
$status here is a local variable which has never been defined before you try to use it in if-condition. So, it's always null.
Maybe you missed
$status = $validation_result['Result']['Status'];
or something like this before checking the condition.
I have an app that has rows, each row contains data. The rows are created by the user (just cloning a sample row).
My ajax function looks like this.
save : function(el) {
//Renaming the properties to match the row index and organize
jQuery('#application-builder-layout .builder-row').each(function(row) {
// Iterate over the properties
jQuery(this).find('input, select, textarea').each(function() {
// Save original name attr to element's data
jQuery(this).data('name', jQuery(this).attr('name') );
// Rewrite the name attr
jQuery(this).attr('name', 'application[rows]['+row+'][elements]['+jQuery(this).attr('name')+']');
});
});
//Looping through each row and saving them seperately with new rowkey
setTimeout(function() {
// Iterate over the layers
jQuery('#application-builder-layout .row-box').each(function(row) {
// Reindex layerkey
jQuery(this).find('input[name="rowkey"]').val(row);
// Data to send
$data = jQuery('#application-builder-layout .row-box').eq(row).find('input, textarea, select');
//$data = $data.add( jQuery('#application-builder-layout') );
jQuery.ajax(jQuery('#form').attr('action'), {
type : 'POST',
data : $data.serialize(),
async : false,
success: function( response ) {
//console.log( response );
}
});
});
}, 500);
},
This is the jQuery, it's application style format so this function is inside a var and is called inside a submit function, the problem is not the ajax, looking at it in the console it saves the data fine, just like I have before.
The Problem I cant get all the data into the database (only the last ajax request) take a look below at "Form Data" it shows what my ajax data looks like and how it's inserting into the DB vs how it should insert, I am using json encode and usually this works, but recently I switched to OOP style coding in PHP so I am not sure if that changes anything?
The PHP:
class MyApp {
const Post_Type = 'page';
public function __construct() {
// register actions
add_action('init', array(&$this, 'init'));
}
public function init() {
// Initialize Post Type
add_action('save_post', array(&$this, 'save_post'));
}
//The main save method
public function save_post($post_id) {
// Empty the builder
if($_POST['rowkey'] == 0) {
$builder = array();
}
$builder['rows'][$_POST['rowkey']] = $_POST['application']['rows'][$_POST['rowkey']];
$builder = esc_sql(json_encode($builder));
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if($_POST['post_type'] == self::Post_Type && current_user_can('edit_post', $post_id)) {
// Update the post's meta field
update_post_meta($post_id, 'MY_DATABASE', $builder);
} else {
return;
}
}
}
The above works fine, except its not inserting the data as an array just inserting the last ajax post call, not each. I am sure in my save method I need to reconfig that somehow, but I am just hacking away and cant find info on the web, so I could really use some insight.
I hope I provided enough.
My code summed up: Just to be clear on whats going on here, let me you some basic HTML of my app.
//This gets cloned and the jQuery renames the rowkey to match the index.
<div class="row-box">
<input type="hidden" name="rowkey" value="0">
<div class="builder-row">
<textarea style="display: block;" name="html"></textarea>
<textarea style="display: block;" name="breakingbad"></textarea>
</div>
</div>
So summed up lets say there is 4 rows, the jQuery renames each row, then loops through each and submits an ajax call for each of them. Then the PHP handles the $_POST, in prior applications working with my custom DB I got it to work but working with wp database I am having issues, maybe I am missing something in my method?
Form Data: the ajax form data looks like this (this is the form data inside headers which can be found in the console(firbug) or network(chrome))
//First element
rowkey:0
application[rows][0][elements][html]:A
application[rows][0][elements][breakingbad]:123
Then if there is another row ajax posts again
//Second element
rowkey:1
application[rows][1][elements][html]:B
application[rows][1][elements][breakingbad]:456
So an and so forth, the database looks like this
{"rows":{"2":{"elements":{"html":"B","breakingbad":"456"}}}}
It should be more like this
{"rows":[{"elements":{"html":"A","breakingbad":"123"},{"elements":{"html":"B","breakingbad":"456"}]}
Holy Smokes Batman: I think I got it, It all resides inside how I handle the $_POST ill update soon with an answer..
The database looks good like this
{"rows":[
{"elements":{"html":"A","breakingbad":"123"}},
{"elements":{"html":"B","breakingbad":"456"}}]
}
Now I can continue to build.. whew this was a MASSIVE headache.
I have a form :
<?php
$attr = array('id'=>'urlSubmit');
$urlInputAttr = array('name'=>'urlInput','value'=>'yourdomain.com','maxlength'=>'50','size'=>'25');
echo form_open('urlSubmission',$attr);
echo form_input($urlInputAttr);
#echo form_submit('urlInput', '');
echo form_close();
?>
a controller called urlsubmission
$this->load->model('domaincheckmodel');
$this->domaincheckmodel->verifyduplicates($this->input->post('urlInput'));
and a function within a model(domaincheckmodel) which basically checks for duplicate records and inserts a new domain:
function verifyduplicates($tldEntered){
# $_POSTed value of urlInput
## Gather if the domain exists in db
$DupDomains = $this->db->get_where('ClientDomain', array('tld'=>$tldEntered));
if($DupDomains->num_rows() > 0 ){
$this->load->view('err/domainexists'); ##domain already used
}
# else, no domain present, insert.
else{
#array of insert values:
$insertNewDomain = array('tld'=>$this->input->post('urlInput',TRUE));
$this->db->insert('ClientDomain', $insertNewDomain);
$this->load->view('success/domainfree'); ##domain is free and has been entered.
}
}
$this->domaincheckmodel->verifyduplicates($this->input->post('urlInput'));
function verifyduplicates($tldEntered){
# $_POSTed value of urlInput
## Gather if the domain exists in db
$DupDomains = $this->db->get_where('ClientDomain', array('tld'=>$tldEntered));
You're passing from the form to the controller to the model, are you sure the post variable is staying populated? Try the above, capture the post variable in the controller and pass it to the model instead of trying to read it in the model itself?
A little clarification on passing parameters to functions. You can do this via whatever is inside the brackets as follows.
Controller:
$myVariable = $this->someModel->someFunction($someParameter)
Model:
function someFunction($variableIWantToPopulateWithSomeParameter)
So someParameter gets passed from the controller to the function name in the model. There is one thing to be aware of though and that is that model function now EXPECTS a parameter and if you don't give it one, ie you call someFunction() you'll get an error. This can be avoided by giving it a default value like this:
function someFunction($myVariable = 1)
What that is going to do is say if I don't get a value passed to me I am going to make $myVariable equal to one, if I do I'll overwrite 1 with the new value. So if you send two calls to that function this is what you can expect:
//$myVariable is going to be 1, the default.
$this->someModel->someFunction();
//$myVariable is going to be 5, the value passed to it
$this->someModel->someFunction(5);
Greets.
{{Solved}}
In order to get POST data you MUST use $this->formHidden in order to hold all the data. Even though variables are inside the they don't get passed if they aren't in some sort of form item.
I am unable to access post data in ZEND.
Path of User -
START
INDEX PAGE
->Submit Page
->Pay Page
I created a controller, extended the Zend Controller, and added an action called payAction. The user can go from the Index Page to the Submit Page. After I have all their data inside variables, I used a form and a submit button to go to the "pay page". However, I cannot get any of the POST data.
public function payAction()
{
$data = $this->getRequest();
}
I have tried putting getRequest, getParam, getRawBody inside that controller function.
In the page itself I have tried.
echo 'Hello';
echo $request;
echo $data;
echo $_POST['payZip'];
echo $_POST['data'];
echo $_POST[$data];
echo $request;
echo $this->values['payZip'];
echo $payZip;
echo $this->values['shippingDone'];
echo $stuff;
Is there ANYTHING I can place in my controller or in my view in order to get my post data? I used a form method="post" and a button and it DOES allow me to get to the page. I can see Hello. But NONE of the post data is available.
Any assistance would be appreciated.
Thank you.
-- Update
$data = $this->getRequest();
$param = $this->_request->getParam('payZip');
if($this->getRequest()->isPost())
{
print_r($this->_getAllParams());
echo $param;
}
Doing that gives me -
HelloArray ( [controller] => wheel [action] => pay [module] => default [shipping] => UPS Ground [payPal] => Secure Payment System )
But I still can't print payZip... I did echo and nothing comes out.
To get parameters from Zend Framework you need to do this in the Action Controller:
$data = $this->_request->getParams();
You can also get individual params like this
$param = $this->_request->getParam('payZip');
What it appears your doing wrong is you're only getting the "request object". You need to then call that objects method to get the request data.
Here's some simple code I often use when testing parameters:
public function indexAction()
{
#::DEBUG::
echo '<pre>'; print_r($this->_request->getParams()); echo '</pre>';
#::DEBUG::
}
This will show all your parameters. What you will notice is that you will also get the names of the Module, Controller and Action with your params.
EDIT
Ps. If you're trying to use the parameter in the view script you need to do this:
echo $this->data['payZip'];
echo $this->param;
In your Action Controller, you save your data to the "view" object by doing this:
$this->view->myVariable = 'Hello';
But when you're in a view script, you are IN the view script, so $this represents $this->view from the action controller.
So, you access the variable like this:
echo $this->myVariable;
Wrapping everything into a bigger code chunk for understanding:
Your Controller
public function indexAction()
{
// get all parameters and pass them to the view
$this->view->params = $this->_request->getParams();
// get an individual parameter and pass it to the view
$this->view->payZip = $this->_request->getParam('payZip');
}
Your View Script
<!-- Dump all parameters -->
<pre><?php print_r($this->params); ?></pre>
<!-- Print payZip -->
<p>My PayZip is: <?php echo $this->payZip; ?></p>
<!-- Print payZip from full parameter array -->
<p>My PayZip (array) is: <?php echo $this->data['payZip']; ?></p>
I hope that helps!