PHP Form jQuery On Submit

I am using a CMS called expression engine.  It develops it's own forms. Here is an example:

Code on page:
		{exp:cartthrob:add_to_cart_form
			id="mail_info"
			return="{template_group}/view_cart/"
			class='form-horizontal'
			entry_id="{entry_id}"
			no_tax="yes"
			no_shipping="yes"
			allow_user_price="yes"
			subscription_plan_id="1"
			}

Open in new window

Rendered Code:
<form id="mail_info" class="form-horizontal" action="/store/29" method="post" novalidate="novalidate" data-dpmaxz-eid="5">
<div class="hiddenFields">
<input type="hidden" value="114" name="ACT">
<input type="hidden" value="/index.php?/store/29" name="RET">
<input type="hidden" value="store/29" name="URI">
<input type="hidden" value="cb8e5b489f04be74fa74fffd727bd3cc" name="FRM">
<input type="hidden" value="store/view_cart/" name="return">
<input type="hidden" value="29" name="entry_id">
<input type="hidden" value="1TUIrKaILcaDYniewO0IBTcJsIWMvvaCKUZ4v5FsktNPg5zuqRta0+jClTDZoOAAtIkC2tc8P3AfFmqHjFdRfw==" name="AUP">
<input type="hidden" value="Jbhbdxnq/FizDDKf2T4yE6UZSw+xI5PCXBU3Dq+xUpyRdJ34GFuvQ5SeZEK84Vo7FEN1rsjDXHyzJ2OffGLSHA==" name="PI">
<input type="hidden" value="zpCPzmYfcYKrYN8huytyAgrKn04XpV72F13VzSDmwASqT9pxgH86rov+G7CSoa2YRopSQ2aY17GTDIU+6S1AHA==" name="AUW">
<input type="hidden" value="lfd4zh3RnxIhUBgib91dWdCmt3P0i8WRGeugdX1Mu+RR4I90+6J6Wfe4PeAxNgBI2F7WwVLcUoPoJr+NZNoItQ==" name="AUS">
<input type="hidden" value="eDgkkhR2caGm12HPR6POb6Dnq9PPDExaC1KnqsbmZKZpWOYt4KkTwWufkssvvepxc+KOEYTvvTZHRNA21yE7Iw==" name="OTF">
<input type="hidden" value="x9Rqg04BU4ponuwaKCMO95uJ5b6EwMufrh1bIfyjVLO00yIc9CHy1EtxmbJSs3QMeHTzP2tXVxtInsSOSRkAMw==" name="LIC">
<input type="hidden" value="c1j9ElkgUYEaOgsfAPM4WtY+K3vOdpZRIlwVH8cmzpMps/fUs13GcxxHXuQa5nh26hBazm/BHWF/NHeICeumBQ==" name="ERR">
<input type="hidden" value="2OxVyDYECXRK9c8lGl28/txIP6bxOnnX6749e9c6cRA/NnQN64OLuGx238TapS4a9TcPKPKTFkQ4VM+qIM4HBw==" name="RLS">
<input type="hidden" value="gMvGLJBMCcu3+beqzZNiImLfvZz7/816S40iJyvlAY8To3Rcvbp3teVwvH0m2RC6IRk22RDGs8HfSrnBYWjutA==" name="NTX">
<input type="hidden" value="P2Jrax61K8ywG+0wbcTHGbrJrEm+nD4hbuLFJGfL/nwSvahwjaTiHu5Gg9wO2czxBASe2zMrgEldmZU9D2uBOg==" name="NSH">
<input type="hidden" value="1" name="site_id">
<input type="hidden" value="afc94b8d0c7f521209fd20dc71cb67b1e68cdd86" name="csrf_token">

Open in new window


The code on the page returns to the new page when the form is processed.  However, I need to send an email with all of the form inputs.  I cannot seem to figure out a way to do a if(isset($_POST['mail_info'] when it gets to the next page.  It is like the form was never sent.  The action is on the same page as the form but that does not seem to work either.

Is there a way to do it with jQuery / Javascript?
LVL 7
rgranlundAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gr8gonzoConsultantCommented:
Why not send the email when the form is being processed and before the redirection?
0
rgranlundAuthor Commented:
That sounds good.  Can you show me a brief example?  This is outside of anything I have ever done before so I'm not sure where to start.
0
gr8gonzoConsultantCommented:
Where is the form processed? Do you have access to that code?
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

rgranlundAuthor Commented:
@gr8gonzo
Yes, I have all of the php code to send the email.  I would like the php to run on the page that the form is on.  What would you like to see?
0
gr8gonzoConsultantCommented:
So when the form is submitted, it goes to a page where the form data gets processed, and then the user is redirected to another page. I'm referring to the code that processes the form data, not the e-mailing code. If you have the code, can you post it?
0
rgranlundAuthor Commented:
@gr8gonzo

I think this is it.
public function add_to_cart()
	{
		// cartthrob_add_to_cart_start hook
		if ($this->EE->extensions->active_hook('cartthrob_add_to_cart_start') === TRUE)
		{
			//@TODO work on hook parameters
			//$edata = $EXT->universal_call_extension('cartthrob_add_to_cart_start', $this, $_SESSION['cartthrob']);
			$this->EE->extensions->call('cartthrob_add_to_cart_start');
			if ($this->EE->extensions->end_script === TRUE) return;
		}
		
		$data = array(
			'entry_id' => $this->EE->TMPL->fetch_param('entry_id'),
			'quantity' => ($this->EE->TMPL->fetch_param('quantity') !== FALSE) ? $this->EE->TMPL->fetch_param('quantity') : 1,
			'class' => 'product',
		);
		
		foreach ($this->EE->TMPL->tagparams as $key => $value)
		{
			if (preg_match('/^item_options?:(.*)$/', $key, $match))
			{
				if ( ! isset($data['item_options']))
				{
					$data['item_options'] = array();
				}
				
				$data['item_options'][$match[1]] = $value;
			}
		}

		if (bool_string($this->EE->TMPL->fetch_param('shipping_exempt')))
		{
			$data['no_shipping'] = TRUE;
		}
		if (bool_string($this->EE->TMPL->fetch_param('no_shipping')))
		{
			$data['no_shipping'] = TRUE;
		}

		if (bool_string($this->EE->TMPL->fetch_param('tax_exempt')))
		{
			$data['no_tax'] = TRUE;
		}
		if (bool_string($this->EE->TMPL->fetch_param('no_tax')))
		{
			$data['no_tax'] = TRUE;
		}
		
		$data['product_id'] = $data['entry_id'];
		
		if ( ! $data['entry_id'])
		{
			$this->EE->cartthrob->set_error(lang('add_to_cart_no_entry_id'));
		}
		
		if ( ! $this->EE->cartthrob->errors())
		{
			$entry = $this->EE->product_model->get_product($data['entry_id']);
			
			//it's a package
			if ($entry && $field_id = $this->EE->cartthrob_field_model->channel_has_fieldtype($entry['channel_id'], 'cartthrob_package', TRUE))
			{
				$data['class'] = 'package';
				
				$this->EE->load->library('api');
				
				$this->EE->api->instantiate('channel_fields');
				
				if (empty($this->EE->api_channel_fields->field_types))
				{
					$this->EE->api_channel_fields->fetch_installed_fieldtypes();
				}
				
				$data['sub_items'] = array();
				
				if ($this->EE->api_channel_fields->setup_handler('cartthrob_package'))
				{
					$field_data = $this->EE->api_channel_fields->apply('pre_process', array($entry['field_id_'.$field_id]));
					
					foreach ($field_data as $row_id => $row)
					{
						$item = array(
							'entry_id' => $row['entry_id'],
							'product_id' => $row['entry_id'],
							'row_id' => $row_id,
							'class' => 'product',
						);
						
						$item['item_options'] = (isset($row['option_presets'])) ? $row['option_presets'] : array();
						
						$row_item_options = array();
						
						if (isset($_POST['item_options'][$row_id]))
						{
							$row_item_options = $_POST['item_options'][$row_id];
						}
						else if (isset($_POST['item_options'][':'.$row_id]))
						{
							$row_item_options = $_POST['item_options'][':'.$row_id];
						}
						
						$price_modifiers = $this->EE->product_model->get_all_price_modifiers($row['entry_id']);
						
						foreach ($row_item_options as $key => $value)
						{
							//if it's not a price modifier (ie, an on-the-fly item option), add it
							//if it is a price modifier, check that it's been allowed before adding
							if ( ! isset($price_modifiers[$key]) || ! empty($row['allow_selection'][$key]))
							{
								$item['item_options'][$key] = $this->EE->security->xss_clean($value);
							}
						}
						
						$data['sub_items'][$row_id] = $item;
					}
				}
			}
			elseif($entry)
			{
				// it's a product... don't need to do anything extra
				// but we need to check for it... else the class gets killed and we dont' want that. 
			}
			else
			{
				// it's a dynamic product. kill the class
				if (isset($data['class']))
				{
					unset($data['class']); 
				}
			}
						
			$item = $this->EE->cartthrob->cart->add_item($data);
			
			if ($item && $this->EE->TMPL->fetch_param('permissions'))
			{
				$item->set_meta('permissions', $this->EE->TMPL->fetch_param('permissions'));
			}
			
			if ($item && bool_string($this->EE->TMPL->fetch_param('license_number')))
			{
				$item->set_meta('license_number', TRUE);
			}
	
			// cartthrob_add_to_cart_end hook
			if ($this->EE->extensions->active_hook('cartthrob_add_to_cart_end') === TRUE)
			{
				//@TODO work on hook parameters
				//$edata = $EXT->universal_call_extension('cartthrob_add_to_cart_end', $this, $_SESSION['cartthrob'], $row_id);
				$this->EE->extensions->call('cartthrob_add_to_cart_end', $item);
				if ($this->EE->extensions->end_script === TRUE) return;
			}
		}
		
		$show_errors = bool_string($this->EE->TMPL->fetch_param('show_errors'), TRUE);
		
		$this->EE->session->set_flashdata(array(
			'success' => ! (bool) $this->EE->cartthrob->errors(),
			'errors' => $this->EE->cartthrob->errors(),
			'csrf_token' => $this->EE->functions->add_form_security_hash('{CSRF_TOKEN}'),
		));
		
		if ($show_errors && $this->EE->cartthrob->errors() && ! AJAX_REQUEST)
		{
			return show_error($this->EE->cartthrob->errors());
		}
		
		$this->EE->cartthrob->cart->save();
		
		$this->EE->template_helper->tag_redirect($this->EE->TMPL->fetch_param('return'));
	}

Open in new window


If not, my second guess is this:
	public function add_to_cart_form()
	{
		if ( ! $this->EE->session->userdata('member_id') && $this->EE->TMPL->fetch_param('logged_out_redirect'))
		{
			$this->EE->template_helper->tag_redirect($this->EE->TMPL->fetch_param('logged_out_redirect'));
		}
		
		$this->EE->load->library('form_builder');
		
		$this->EE->load->model('subscription_model');
		
		$this->EE->form_builder->initialize(array(
			'form_data' => array(
				'entry_id',
				'quantity',
				'secure_return',
				'title',
				'language',
				'return'
			),
			'encoded_form_data' => array_merge(
				$this->EE->subscription_model->encoded_form_data(),
				array(
					'shipping' => 'SHP',
					'weight' => 'WGT', 
					'permissions'	=> 'PER',
					'upload_directory' => 'UPL',
					'class'		=> 'CLS',
				)
			),
			'encoded_numbers' => array_merge(
				$this->EE->subscription_model->encoded_numbers(),
				array(
					'price' => 'PR',
					'expiration_date' => 'EXP',
				)
			),
			'encoded_bools' => array_merge(
				array(
					'allow_user_price' => 'AUP',
					'allow_user_weight' => 'AUW',
					'allow_user_shipping' => 'AUS',
					'on_the_fly' => 'OTF',
					'show_errors' => array('ERR', TRUE),
					'license_number' => 'LIC',
				)
			),
			'array_form_data' => array(
				'item_options',
			),
			'encoded_array_form_data' => array(
				'meta'				=> 'MET',
			),
			'classname' => 'Cartthrob',
			'method' => 'add_to_cart_action',
			'params' => $this->EE->TMPL->tagparams,
		));
 		
		// can't just shove these in the encoded bools, or they will always be FALSE by default unless set. 
		// since the field type overrides them, we don't even want them set here unless explicitly set. 
		foreach ($this->EE->subscription_model->encoded_bools() as $key => $value)
		{
			if ($this->EE->TMPL->fetch_param($key))
			{
				$this->EE->form_builder->set_encoded_bools($key, $value)->set_params($this->EE->TMPL->tagparams);
			}
		}

		if (bool_string($this->EE->TMPL->fetch_param('no_tax')))
		{
			$this->EE->form_builder->set_encoded_bools("no_tax", 'NTX')->set_params($this->EE->TMPL->tagparams);
		}
		elseif (bool_string($this->EE->TMPL->fetch_param('tax_exempt')))
		{
			$this->EE->form_builder->set_encoded_bools("tax_exempt", 'NTX')->set_params($this->EE->TMPL->tagparams);
		}
		
		if (bool_string($this->EE->TMPL->fetch_param('no_shipping')))
		{
			$this->EE->form_builder->set_encoded_bools("no_shipping", 'NSH')->set_params($this->EE->TMPL->tagparams);
		}
		elseif (bool_string($this->EE->TMPL->fetch_param('shipping_exempt')))
		{
			$this->EE->form_builder->set_encoded_bools("shipping_exempt", 'NSH')->set_params($this->EE->TMPL->tagparams);
		}
		
		
		$data = array_merge(
			$this->EE->cartthrob_variables->item_option_vars($this->EE->TMPL->fetch_param('entry_id')),
			$this->EE->cartthrob_variables->global_variables(TRUE)
		);

		$this->EE->cartthrob_variables->add_encoded_option_vars($data);
		
		foreach ($this->EE->TMPL->var_single as $var)
		{
			if (preg_match('/^inventory:reduce(.+)$/', $var, $match))
			{
				$data[$match[0]] = '';
				
				$var_params = $this->EE->functions->assign_parameters($match[1]);
				
				if ( ! empty($var_params['entry_id']))
				{
					if (empty($var_params['quantity']))
					{
						$var_params['quantity'] = 1;
					}
					else
					{
						$var_params['quantity'] = sanitize_number($var_params['quantity']);
					}
					
					$this->EE->form_builder->set_hidden('inventory_reduce['.$var_params['entry_id'].']', $var_params['quantity']);
				}
			}
		}
		
		$this->EE->load->library('languages');
		
		$this->EE->languages->set_language($this->EE->TMPL->fetch_param('language'));
		
		$this->EE->form_builder->set_content($this->EE->template_helper->parse_variables_row($data));
		
		return $this->EE->form_builder->form();
	}

Open in new window

0
gr8gonzoConsultantCommented:
So the second one looks like it's the function that generates the form code. The first one looks like it processes AJAX requests to add items to the cart, so if you added 3 items to the cart, it would run that first piece of code 3 times (just a guess based on what I'm seeing).

That said, do you want to send out your email when the user adds something to the cart, or when they check out (I'm assuming the latter) ?
0
rgranlundAuthor Commented:
No.  I want to send an email when added to the cart.  On this particular page the customer will never reach the checkout.  The product is not being sold currently, so what they do is configure everything in the cart and submit and it send the info to a rep.
0
gr8gonzoConsultantCommented:
Okay, so in the first section of code, just add your e-mailing PHP code AFTER this line:

$this->EE->cartthrob->cart->save();
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rgranlundAuthor Commented:
My Service provider uses SendGrid.  Do you see any issues with the following PHP?  Especially the require part?  Also, it does not seem to have run. But sometimes that email relay takes some time.

require("sendgrid/sendgrid-php.php");

$sendgrid = new SendGrid('USERNAME', 'PASSWORD');

$email = new SendGrid\Email();


$fname = $_POST['item_options']['first_name'];
$lname = $_POST['item_options']['last_name'];

$fullname = $fname. '' . $lname;

if(isset($_POST['item_options']['gender'])) {
	$gender = $_POST['item_options']['gender'];
} else {
	$gender= '';	
}

if(isset($_POST['item_options']['marital_status'])) {
	$marital_status = $_POST['item_options']['marital_status'];
} else {
	$marital_status = '';	
}

if(isset($_POST['item_options']['minors'])) {
	$minors = $_POST['item_options']['minors'];
} else {
	$minors = '';	
}
$professional_cyclist = $_POST['item_options']['professional_cyclist'];
$triathlete = $_POST['item_options']['triathlete'];

if(isset($_POST['item_options']['association_membership'])) {
		$association_membership = $_POST['item_options']['association_membership'];
	} else {
		$association_membership = '';	
	}
	
$product_deductible = $_POST['item_options']['product_deductible'];

if(isset($_POST['item_options']['product_liability'])) {
	$product_liability = $_POST['item_options']['product_liability'];	
} else {
	$product_liability = '';	
}
if(isset($_POST['item_options']['product_medical'])) {
		$product_medical = $_POST['item_options']['product_medical'];
	} else {
		$product_medical = '';	
	}
if(isset($_POST['item_options']['product_contact'])) {
	$product_contact = $_POST['item_options']['product_contact'];	
} else {
	$product_contact = '';	
}


$type_bicycle = $_POST['item_options']['type_bicycle'];


if(isset($_POST['item_options']['year_built'])) {
	$year_built = $_POST['item_options']['year_built'];
} else {
	$year_built = '';	
}

if(isset($_POST['item_options']['manufacturer'])) {
	$model = $_POST['item_options']['model'];
	} else {
		$model = '';
		}

if(isset($_POST['item_options']['serial_number'])) {
	$serial_number = $_POST['item_options']['serial_number'];
	} else {
		$serial_number = '';
	}

$bicycle_material = $_POST['item_options']['bicycle_material'];
$usage = $_POST['item_options']['usage'];

if(isset($_POST['item_options']['purchase_date'])) {
	$purchase_date = $_POST['item_options']['purchase_date'];
} else {
	$purchase_date = '';
}	
if(isset($_POST['item_options']['purchase_price'])) {
	$purchase_price = $_POST['item_options']['purchase_price'];
} else {
	$purchase_price = '';	
}

$used = $_POST['item_options']['used'];


if(isset($_POST['item_options']['accessories_value'])) {
	$accessories_value = $_POST['item_options']['accessories_value'];
} else {
	$accessories_value = '';	
}

if(isset($_POST['item_options']['attached_accessories'])) {
	$attached_accessories = $_POST['item_options']['attached_accessories'];
} else {
	$attached_accessories = '';	
}

$bicycle_location = $_POST['item_options']['bicycle_location'];
$location_address = $_POST['item_options']['location_address'];
$location_city = $_POST['item_options']['location_city'];
$location_state = $_POST['item_options']['location_state'];
$location_zip = $_POST['item_options']['location_zip'];
$contact_email = $_POST['item_options']['contact_email'];


$email
    ->addTo('robert@baycreative.com')
    ->setFrom('sales@spokeinsurance.com')
    ->setSubject('Spoke Sales Lead')
	->setHtml('<b>Name::</b> '.$fullname.'<br />
	<b>Email:: </b> '.$contact_email.
	'<br /><b>Gender:: </b> '.$gender.
	'<br /><b>Marital Status:: </b> '.$marital_status.
	'<br /><b>Minors:: </b> '.$minors.
	'<br /><b>Professional Cyclist:: </b> '.$professional_cyclist. 
	'<br /><b>Triathlete:: </b> '.$triathlete.
	'<br /><b>Association Membership:: </b> '.$association_membership.
	'<br /><b>Deductible:: </b> '.$product_deductible.
	'<br /><b>Liability:: </b> '.$product_liability.
	'<br /><b>Medical:: </b> '.$product_medical.
	'<br /><b>Contact:: </b> '.$product_contact.
	'<br /><b>Type of Bicycle:: </b> '.$type_bicycle.
	'<br /><b>Year Built:: </b> '.$year_built.
	'<br /><br /><b>Model:: </b> '.$model.
	'<br /><b>Serial Number:: </b> '.$serial_number.
	'<br /><b>Bicycle Material:: </b> '.$bicycle_material.
	'<br /><b>Usage:: </b> '.$usage.
	'<br /><b>Purchase Date:: </b> '.$purchase_date.
	'<br /><b>Purchase Price:: </b> '.$purchase_price.
	'<br /><b>New or Used:: </b> '.$used.
	'<br /><b>Accessories Value:: </b> '.$accessories_value. 
	'<br /><b>Attached Accessories:: </b> '.$attached_accessories.
	'<br /><b>Bicycle Location:: </b> '.$bicycle_location. 
	'<br /><b>Location Address:: </b> '.$location_address.
	'<br /><b>Location City:: </b> '.$location_city. 
	'<br /><b>Location State:: </b> '.$location_state. 
	'<b>Location Zip:: </b> '.$location_zip);


$sendgrid->send($email);

Open in new window

0
gr8gonzoConsultantCommented:
I don't see a problem off-hand. The only thing I would double-check is to make sure that the require() uses the correct folder. If the AJAX request goes to a different folder, then you might have to adjust the path in your require(). For example, let's say yourpage.php does the AJAX post to ajax/addcart.php, and you have the following filesystem structure:

/yourpage.php
/ajax/addcart.php
/sendgrid/sendgrid-php.php

...then your require() would have to go up one folder:
require("../sendgrid/sendgrid-php.php");

If you're not sure what folder the AJAX request runs from, you can just log the output of getcwd() somewhere:

file_put_contents("rgranlund.log", "AJAX is running from " . getcwd());

...then add an item to the cart and look for rgranlund.log in your files on the server. Make sense?
0
rgranlundAuthor Commented:
It worked.  It was actually a different method that I needed to put the code it.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.