Adding Google Analytics tracking code to contact form - php

I'd like to add Google event tracking to my PHP contact form. Doing so requires me to add a particular value to the 'onsubmit' attribute of the element. My PHP file already has an 'onsubmit' attribute defined. When I delete that attribute and enter the required Google code, nothing happens when I click the 'Submit' button (i.e. form does not submit, 'Thank You' page does not load, etc).
Here is the existing PHP code:
<form
class="cpp_form"
name="<?php echo $this->prefix; ?>_pform<?php echo '_'.$this->print_counter; ?>"
id="<?php echo $this->prefix; ?>_pform<?php echo '_'.$this->print_counter; ?>"
action="<?php $this->get_site_url(); ?>" method="post" enctype="multipart/form-data"
onsubmit="return <?php echo $this->prefix; ?>_pform_doValidate<?php echo '_'.$this->print_counter; ?>(this);">
Here is the Google code I need to enter for onsubmit:
_gaq.push([‘_trackEvent’, ‘button’, ’clicked’, ’contact us’,, ’true’])
Any ideas on how to do this/what I'm doing wrong?
I've also tried entering the Google code as the value for the "onclick" attribute. When I do that, the form can successfully be submitted, but it does not show up as an 'event' in Google Analytics.

Couple of things:
1) The GA code you posted shows smart-quotes. I'm not sure whether that's just a c/p thing posting here or if that's what you used in your actual code, but smart-quotes is invalid javascript syntax.
2) There are several ways you can do this. One way is to add it to your onsubmit as you tried. You don't need to replace the current stuff in there. Just add it to it. Since your current thing in there is returning something, you will want to add it before:
onsubmit="_gaq.push(['_trackEvent', 'button', 'clicked', 'contact us',,'true']); return <?php echo $this->prefix; ?>_pform_doValidate<?php echo '_'.$this->print_counter; ?>(this);">
Alternatively, you can look for where that xxx_pform_doValidate_xxx() function is defined and put your GA code in there.
3) To be clear, you are tracking that the form submit button was clicked. In my experience, tracking form submit button clicks has little value, since it does not indicate that the form was successfully submitted, nor does it tell you why submission failed if it failed.

You could add the google code to your validation function or use a separate function where you first put the google code and then return the value of your validation function. Or add it inline before the return statement...
But as you have a "Thank You" page, you could also track that instead although that will not give you the client- and server-side unvalidated submissions.

Related

Retrieving values posted using the link

I am trying to submit a form using a hyperlink and it is not posting values onto the next page.Here is my code form:
<?php
$email = array('name'=>'accountno','id'=>'accountno','value'=>set_value('email'));
?>
<form method="post" id = "login_form" action="/salesrep/check" name = "login_form" class="custLogin">
<fieldset style="color: #BD1313; width: 440px;"> <input type="hidden" name="submit_type" id="submit_type" value="account_only">
<br><center><label for="customerNo"><b>Customer No:</b></label>
<? echo form_input($email);?>
Submit<? echo form_input($button);?> </center>
<p> </p>
</fieldset>
</form>
The code on the next page looks like this:
<?
print_array($_POST);
die();
?>
When i use the button here,it posts values to next page successfully.BUT I HAVE not been able to post values using the hyperlink on onclick event. Where i am making mistake??
Why i am getting empty array when i am already inserting value in the text box.?? Or is there any way i could post values using the link and retrieve them in the next page???
The real problem is that you are trying to use a link plus some JavaScript to submit a form in the first place. Don't do this. Buttons inform users that they will submit the form. They will show up in screen readers when they are in forms mode (a link with some JavaScript won't). They "just work".
If you insist on using a link and some JavaScript, then the reason that your code doesn't work is that the JavaScript runs, the form starts to submit, then the link is followed and a GET request is made to the page instead.
Normally you could call preventDefault on the event to stop this, but you are using old style intrinsic event attributes so you need to return false; from there instead.
Recommended reading: Progressive Enhancement and Unobtrusive JavaScript

Use PHP to track links

I have various links in my website that point to a specific form.
Whenever someone fills out the form, I want to be able to know what link led them to the form.
I want to do this without having to create an individual line of PHP code for every link I create in the. Instead, I want to have some PHP code that picks up something from that link, and maybe inserts it into a hidden text box that gets its value or text from something that I tag in the link.
For example:
User clicks a link.
That link directs them to a form.
The link carries an identification that activates PHP code
When I recieve the form, I know what link was clicked to get to that form.
I want it to work with links in emails I send out as well.
Based on the information in your post, it sounds like you just want to send a token/ id.
Goto Form
Now on the form you can grab the token:
$token = $_GET['token']; // use proper testing first
Then use a switch or if statements to run whichever code you need.
<input type="hidden" value="<?php echo $token; ?>">
Additional:
As the //use proper testing first comment indicates, you should make sure the token being passed is valid and sanitized in case of attack. One option is to have tokens stored in a database when generated and then compared when validating. Also look into htmlspecialchars() and even strip_tags() for sanitizing.
If the token fails to validate, you should not output and should even have a warning message/redirect that there was an error.
You can use HTTP Referer to achieve this. In PHP, you can use
$referer = $_SERVER['HTTP_REFERER']
Use this for example :
if (isset($_SERVER['HTTP_REFERER']))
{
$ref = $_SERVER['HTTP_REFERER'];
}
then in your form something like:
<input type="hidden" value="<?php echo htmlspecialchars($ref, ENT_QUOTES); ?>" name="ref" />

Simple contact form with modal response

Alright, I know there are many questions/answers for a modal contact form, but I would like to know how I can have a normal contact form on the page and when submitted, the PHP action is popped up in a modal, saying "Thanks for contacting us", or something along those lines, and then the ability to close. I've done HTML contact forms and hooked in the PHP action before, just never in a modal... Any simple solutions (without the use of plugins)?
If anyone has this question and wants it answered, please be sure to vote up.
If you want to have a javascript-free solution, then your form-handling script will need to be able to present all states of the form. These include:
initial unfilled form
response to first submission which may be:
display of partially or incorrectly filled form with errors marked
thank-you message
response to thank-you message
A modal popup is only a translucent container element (e.g. <div>) styled to be z-positioned on top of all the other html (except its children) and to cover the entire viewport. It contains a form and anything else you might like. When it is not in use, its display attribute is set to none.
So your php form handler might work something like this:
$modalclass='modalhide';
$filteredpost=array();
if(isset($_POST['submit1']){ //user submitted form data
//validate submitted data
$filteredpost = my_cleanup_function($_POST);
if(my_form_is_good($filteredpost){
$modalclass='modalshow';
$filteredpost=array();
}
}
echo <<< EOF
<form method='POST' name='mainform' action='myhandler.php'>
//other form fields
<input type='submit' name='submit1'>
</form>
<div class='$modalclass'>
<form name='thanksmodal' method='POST' action='myhandler.php'>
//content of some sort
<input type='submit' name='thankssubmit'>
</form>
</div>
EOF;
The AJAX method is similar except that a javascript intercepts the submit button actions, submits to a form-handling script asynchronously and presents the results. There are lots of javascript libraries around to make this easier. jQuery and jQuery-UI are my two favourites.

Having Problems with a PHP Contact Form Inside DIV Set to Display:none by Default

We're using PHP to build a product page for a gallery website that's using GetSimple 3.0 CMS. We are trying to create a contact form that is displayed when you click a button. By default the contact form is in a DIV that's set to display: none. When you click the button it displays: block. When a user clicks the submit button for the form and calls the action it loads the contact.php file and resets the DIV to display: none resulting in the user not seeing the conformation text that their form was submitted. You can only see it by clicking on the contact button again and displaying that DIV to block manually.
We'd like the contact form DIV to persist after the submit button is clicked. I don't think showing our code would be helpful. We're just trying to find a way to implement this idea if possible.
At present our website is still early in it's development stage and it's still being hosted locally.
Thanks for any help.
use ajax submission of that particular form so that focus will not loss even the page will not be refreshed
If you can edit PHP code used for building the page, you can always display the style dynamically depending on the request, like this:
<div style="display:<?php echo (isset($_REQUEST['answer'])) ? 'block' : 'none';?>>
Thank you!
</div>
<form action="contact.php" method="post">
<input type="hidden" name="answer" />
...
</form>
You can also submit a form without reloading the page, e.g. with JQuery.Forms
If both the form and the PHP file are located in Contact.php, you could consider using this:
<div id="formWarp" <? if($_POST["contact"] == "true"){ echo 'style="display:none" '; } ?>>
<form method="POST" action="Contact.php">
<input type="text" name="something"/>
<input type="hidden" name="contact" value="true"/>
</form>
You can include any other <input>'s inside the form.
EDIT: Completely changed to reflect new information obtained to more directly address the problem.
Reading your above comments I'm fairly confident we are looking at the wrong function to edit. The wrapper element is not present in the function you posted which is what needs to have it's display toggled.
once you find that block of code we can edit it to look for the presence of post data which would indicate that the page is being loaded after a form submission has occurred (I can't promise that this won't cause it to trigger at the wrong time if there is more than one form on this page) and write in a style attribute to overwrite the default value if tested true.
Some where in that plugin there will be something defining the forms wrapper element
$html = '<div id="some-unique-id" class="some-class-name">';
You can break up this line and put a test for post data adding an inline style attribute if found
$html = '<div id="some-unique-id" class="some-class-name"'; //tag left open
if(isset($_POST) && (count($_POST))){ //Some Post Data Exists
$html .= ' style="display:block;"'; //Add display overwrite
}//Some Post Data Exists
$html .= '>'; //close the tag
The test we are performing here is if(isset($_POST) && (count($_POST))){ which is checking to make sure that A) $_POST exists and B) it has at least one element (this is using type juggling to convert a numeric result from count() into its Boolean equivalent (where anything greater than 0 will test true)
Now, as i mentioned, there may be more than one form on this page and it is possible it will be displayed afterwards which would auto show your contact form when you don't want to have it showing. Based on the example you provided in a comment it looks like this function exists within a class. If the block of code we are looking for exists within the same class it might be possible to leverage the id attribute to restrict the check to post data from the form you are interested.
$html = '<div id="some-unique-id" class="some-class-name"';
//Check for contact form specific post data
//(if $this->id is within scope and still the same)
if(isset($_POST) && (isset($_POST['p01-contact' . $this->id]))){
$html .= ' style="display:block;"'; //Add display overwrite
}//Post Data Exists
$html .= '>';
In this test we are hoping that $this exists and the attribute id of $this is the same as it was at the time that the form was originally drawn so we can look for post data that is related to the specific contact form. (the name we are looking for is based off of the code example you posted as a comment)
Unfortunately without looking at the source of the site/plugin it will be impossible for me to tell you where you can find what you are looking for. Once you find it though one of these two scenarios should hopefully take care of your problem.
Is this a publicly available plugin we could look at or something developed in-house?

help with javascript confirmation dialog

So here's my situation: I have a form that validates with PHP. I want to make it so that if the form fails validation, the user is forced to click through a confirmation dialog before they navigate to another page (the form is fairly large and they don't want to accidentally leave it before it's saved). I'm going about this like so:
see updated function below,
Basically use php within the function to either set the body to present the confirmation or do nothing depending on the error status of my form. Nothing happens when the form isn't submitted and I click a link, good. When the form is displaying errors and I click a link the confirmation dialog will appear but canceling it causes it to reappear. If I cancel it a second time the page request will go through even though it's not supposed to. I'm not that familiar with javascript so I'm not sure what's going on. Is there a better way I should be going about this?
Edit: I figured it out, it was a combination of things. The first was a really dumb mistake on my part: I was calling the onlick on both tags AND the tags for each link in my list, hence why the box popped up twice.
the second piece was that even though my function already returns bool, the onclick requires an explicit return declaration. I was doing:
<a onclick="forceConfirm();" href="somepage.html">Blah</a>
When it should have been:
<a onclick="return forceConfirm();" href="somepage.html">Blah</a>
Then just edit the PHP so that forceConfirm always returns true when the form hasn't been submitted, bypassing the confirmation:
function forceConfirm(){
<?php
if($form->errorStatus){
echo 'if(confirm("Are you sure you want to navigate away from this page? All unsaved changes will be lost.")){'."\n".
'return true;'."\n".'}'."\n".
'else{ return false;}';
}
else{ echo 'return true;';}
?>
}
Now I just need to figure out how to use jQuery to apply this to all links without having to put onclick events all over the place....
You can use confirm() like this:
if(confirm("Are you sure you want to proceed?")){
document.location = 'confirmed redirect url...';
}
else{
document.location = 'cancel redirect url...';
}
Then you'd wrap that in the same PHP block as in your example, displaying it if necessary and hiding it if not.

Categories