Jump to content

Need help with .js & .php form template!


Win

Recommended Posts

forms.js.txtform.txtMailHandler.php.txt

 

I am a photographer with a strong design and coding background trying to make myself a new website.I'm trying to tweak a template to suit my needs, and I am having considerable trouble with the Contact Form page. I am very familiar with html and css, but js is not my strong suit and I have never worked with php before. If anyone could help me by letting me know where/what I need to edit for the submit button to make the form information go to my email I would greatly appreciate it. I have tried editing what I thought was right, and it still doesn't work. I have given up on my edited files and reverted back to the original template files because I'm sure the files I have been editing are beyond repair at this point. I really need to get this site up and running ASAP, but I am at my wits end with this form. Everything else on the form seems to work fine. These are my thoughts:

  • [*] [*]The action element of the form tag is set to "#". That's not right, but I'm not sure what to put there. And there is no method element.[*] [*]The owner-email on the .js page is also set to #, so I'm sure I need to put in the email address there. I'm just not sure about the syntax.[*] [*]There is also a spot in the .php file that I feel needs to have my email address also, but again, I'm unsure of the syntax. [*] [*]Also the a tag href element on the submit button is also set to "#" and I'm not sure where to point it, because it appears that the form should give the user a .js message confirming that the form has been sent...[*]

This is the form code in the html file:

<h2>Contact form</h2><form action="#" id="ContactForm"><div class="success"> Contact form submitted!<br><strong>We will be in touch soon.</strong> </div><fieldset><div class="wrapper"><span class="col1">Name:</span><label class="name">                 <span class="bg"><input type="text" class="input"></span><span class="error">*This is not a valid name.</span> <span class="empty">*This field is required.</span> </label></div><div class="wrapper"><span class="col1">Email:</span><label class="email"><span class="bg"><input type="text" class="input"></span><span class="error">*This is not a valid email address.</span> <span class="empty">*This field is required.</span> </label></div><div class="wrapper"><span class="col1">Message:</span><label class="message"><span class="bg"><textarea rows="1" cols="1"></textarea></span><span class="error">*The message is too short.</span> <span class="empty">*This field is required.</span> </label> </div><div class="btns"><a href="#" class="button1" data-type="submit">Send</a><a href="#" class="button1" data-type="reset">Clear</a></div></fieldset></form>

This is the forms.js file:

//forms;(function($){$.fn.forms=function(o){return this.each(function(){var th=$(this),_=th.data('forms')||{errorCl:'error',emptyCl:'empty',invalidCl:'invalid',notRequiredCl:'notRequired',successCl:'success',successShow:'4000',mailHandlerURL:'bin/MailHandler.php',ownerEmail:'support@guardlex.com',stripHTML:true,smtpMailServer:'localhost',targets:'input,textarea',controls:'a[data-type=reset],a[data-type=submit]',validate:true,rx:{".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},".state":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},".email":{rx:/^(("[w-s]+")|([w-]+(?:.[w-]+)*)|("[w-s]+")([w-]+(?:.[w-]+)*))(@((?:[w-]+.)*w[w-]{0,66}).([a-z]{2,6}(?:.[a-z]{2})?)$)|(@[?((25[0-5].|2[0-4][0-9].|1[0-9]{2}.|[0-9]{1,2}.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2}).){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})]?$)/i,target:'input'},".phone":{rx:/^+?(d[d-+() ]{5,}d$)/,target:'input'},".fax":{rx:/^+?(d[d-+() ]{5,}d$)/,target:'input'},".message":{rx:/.{20}/,target:'textarea'}},preFu:function(){_.labels.each(function(){var label=$(this),inp=$(_.targets,this),defVal=inp.val(),trueVal=(function(){var tmp=inp.is('input')?(tmp=label.html().match(/value=['"](.+?)['"].+/),!!tmp&&!!tmp[1]&&tmp[1]):inp.html()return defVal==''?defVal:tmp})()trueVal!=defVal&&inp.val(defVal=trueVal||defVal)label.data({defVal:defVal}) inp.bind('focus',function(){inp.val()==defVal&&(inp.val(''),_.hideEmptyFu(label),label.removeClass(_.invalidCl))}).bind('blur',function(){_.validateFu(label)if(_.isEmpty(label))inp.val(defVal),_.hideErrorFu(label.removeClass(_.invalidCl)) }).bind('keyup',function(){label.hasClass(_.invalidCl)&&_.validateFu(label)})label.find('.'+_.errorCl+',.'+_.emptyCl).css({display:'block'}).hide()})_.success=$('.'+_.successCl,_.form).hide()},isRequired:function(el){ return !el.hasClass(_.notRequiredCl)},isValid:function(el){ var ret=true$.each(_.rx,function(k,d){if(el.is(k))ret=d.rx.test(el.find(d.target).val()) })return ret },isEmpty:function(el){var tmpreturn (tmp=el.find(_.targets).val())==''||tmp==el.data('defVal')},validateFu:function(el){ el.each(function(){var th=$(this),req=_.isRequired(th),empty=_.isEmpty(th),valid=_.isValid(th)  if(empty&&req)_.showEmptyFu(th.addClass(_.invalidCl))else_.hideEmptyFu(th.removeClass(_.invalidCl)) if(!empty)if(valid)_.hideErrorFu(th.removeClass(_.invalidCl))else_.showErrorFu(th.addClass(_.invalidCl)) })},getValFromLabel:function(label){var val=$('input,textarea',label).val(),defVal=label.data('defVal') return label.length?val==defVal?'nope':val:'nope'},submitFu:function(){_.validateFu(_.labels) if(!_.form.has('.'+_.invalidCl).length)$.ajax({type: "POST",url:_.mailHandlerURL,data:{name:_.getValFromLabel($('.name',_.form)),email:_.getValFromLabel($('.email',_.form)),phone:_.getValFromLabel($('.phone',_.form)),fax:_.getValFromLabel($('.fax',_.form)),state:_.getValFromLabel($('.state',_.form)),message:_.getValFromLabel($('.message',_.form)),owner_email:_.ownerEmail,stripHTML:_.stripHTML},success: function(){_.showFu()}}) },showFu:function(){_.success.slideDown(function(){setTimeout(function(){_.success.slideUp()_.form.trigger('reset')},_.successShow)})},controlsFu:function(){$(_.controls,_.form).each(function(){var th=$(this)th.bind('click',function(){_.form.trigger(th.data('type'))return false})})},showErrorFu:function(label){label.find('.'+_.errorCl).slideDown()},hideErrorFu:function(label){label.find('.'+_.errorCl).slideUp()},showEmptyFu:function(label){label.find('.'+_.emptyCl).slideDown()_.hideErrorFu(label)},hideEmptyFu:function(label){label.find('.'+_.emptyCl).slideUp()},init:function(){_.form=_.me _.labels=$('label',_.form) _.preFu() _.controlsFu() _.form.bind('submit',function(){if(_.validate)_.submitFu()else_.form[0].submit()return false}).bind('reset',function(){_.labels.removeClass(_.invalidCl) _.labels.each(function(){var th=$(this)_.hideErrorFu(th)_.hideEmptyFu(th)})})_.form.trigger('reset')}}_.me||_.init(_.me=th.data({forms:_}))typeof o=='object'&&$.extend(_,o)})}})(jQuery)$(window).load(function() { $('#ContactForm').forms({ownerEmail:'#'})})

And this is the mailhandler.php file:

<?php$owner_email = $_POST["owner_email"];$headers = 'From:' . $_POST["email"];$subject = 'A message from your site visitor ' . $_POST["name"];$messageBody = ""; if($_POST['name']!='nope'){$messageBody .= '<p>Visitor: ' . $_POST["name"] . '</p>' . "n";$messageBody .= '<br>' . "n";}if($_POST['email']!='nope'){$messageBody .= '<p>Email Address: ' . $_POST['email'] . '</p>' . "n";$messageBody .= '<br>' . "n";}else{$headers = '';}if($_POST['state']!='nope'){ $messageBody .= '<p>State: ' . $_POST['state'] . '</p>' . "n";$messageBody .= '<br>' . "n";}if($_POST['phone']!='nope'){ $messageBody .= '<p>Phone Number: ' . $_POST['phone'] . '</p>' . "n";$messageBody .= '<br>' . "n";} if($_POST['fax']!='nope'){ $messageBody .= '<p>Fax Number: ' . $_POST['fax'] . '</p>' . "n";$messageBody .= '<br>' . "n";}if($_POST['message']!='nope'){$messageBody .= '<p>Message: ' . $_POST['message'] . '</p>' . "n";} if($_POST["stripHTML"] == 'true'){$messageBody = strip_tags($messageBody);} try{if(!mail($owner_email, $subject, $messageBody, $headers)){throw new Exception('mail failed');}else{echo 'mail sent';}}catch(Exception $e){echo $e->getMessage() ."n";}?>

Any help would be greatly appreciated!

Edited by Win
Link to comment
Share on other sites

It's kind of hard to read that code without any indenting.

 

That's doing an ajax submit, which means that Javascript sends a request to the server with the form data. The request is here:

 

 

$.ajax({type: "POST",url:_.mailHandlerURL,data:{name:_.getValFromLabel($('.name',_.form)),email:_.getValFromLabel($('.email',_.form)),phone:_.getValFromLabel($('.phone',_.form)),fax:_.getValFromLabel($('.fax',_.form)),state:_.getValFromLabel($('.state',_.form)),message:_.getValFromLabel($('.message',_.form)),owner_email:_.ownerEmail,stripHTML:_.stripHTML},success: function(){_.showFu()}})

 

That tells it which method and URL to use, so that's why it's not defined in the form attributes.

 

As the code is set up right now, a spammer can use that form to send any email to anyone. They can change the subject, CC to any number of addresses, write any message they want, etc. That's because of this line:

 

$headers = 'From:' . $_POST["email"];

 

It's putting the value of $_POST['email'] into the headers without bothering to validate it, so that value in $_POST could be any content that the spammer wants to put in the headers (which could include the actual message text). And, since they are getting the recipient address from $_POST also here:

 

$owner_email = $_POST["owner_email"];

 

then the email could go to anyone, you wouldn't even get it or know that it is being abused. They could add CC addresses in the headers and send a message to any number of people they want.

 

I would change that line to ignore what is submitted and just hard code your email address:

 

$owner_email = 'you@domain.com';

 

If you want to validate the value going into the headers to make sure it is a single email address and nothing else, then you can do that too. If you look up PHP email validation you should find several examples. It may be enough to only check that the value does not contain a semicolon or line break, because if it does then they are trying to add more content to the headers.

Link to comment
Share on other sites

Sorry about the indenting. I am still not sure how to add code to a forum like this while preserving the formatting. I uploaded the files as .txt attachments to the original post if that helps. I see exactly what you're saying about the security of the form. And that is a huge concern. I will look up what you suggested. However, it is really a non-issue if I can't get the forms submit button to behave properly... So in that ajax submit (which I assume is in the .js file??) I should change:

url:_.mailHandlerURL, 
to
url:_.bin/mailhandler.php, 
And no method in the form tag. What about the action element?And what about the a ref url in the submit button?? It is also set to #.
Link to comment
Share on other sites

Leave that part like it is, if you want to change the URL you can change that option near the top where it's defined:

 

mailHandlerURL:'bin/MailHandler.php',

 

There doesn't need to be a method or action because the form only gets submitted via ajax. The form doesn't actually submit, Javascript just collects the data and sends a request to the server with all of the data. If the form submitted then you would see the page refresh, which I assume doesn't happen for you because it's Javascript that sends the data. The href attribute on the link doesn't really matter either, the Javascript code attaches click events to those links to submit or reset the form.

 

As you're testing this, use your browser's developer tools to look for Javascript errors. There are some links in my signature that describe the tools for each browser, the console tab should show error messages if there's a problem.

Link to comment
Share on other sites

I must sound completely clueless, and I guess I kind of am in this area... I'm so sorry. Thank you for trying to help me.So, changed the correct mailhandler url...I added my own email address to this line in the .php file:

$owner_email = 'you@domain.com';
And the only error on the console tab when I am on the contact page is in reference to the google map image that I have posted there next to the form. No form errors at all. :|
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
×
×
  • Create New...