Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Forms.js not working

Status
Not open for further replies.

HVtech

IS-IT--Management
Jul 1, 2010
71
NL
Hi,
I found a template for a website with a nice form on it. This form uses the forms.js script to validate and sends the input to a php script.
I get redirected to the php script, but no variables from the form are getting in the php script.
There is also at the bottom a $ownerEmail variable hard coded, even that one is not showing in the php output.
I'm getting hopeless and don't have the knowledge to solve this, therefor this post and the request for help.
This is the html piece:
HTML:
<h2>Contact Formulier</h2>
									
<form id="ContactForm" method="post" action="mail/MailHandler.php">
	<div>
		<div class="wrapper"><input class="input" type="text" value="Naam"  onblur="if(this.value=='') this.value='Naam'" onFocus="if(this.value =='Naam' ) this.value=''" ></div>
		<div class="wrapper"><input class="input" type="text" value="Email"  onblur="if(this.value=='') this.value='Email'" onFocus="if(this.value =='Email' ) this.value=''" ></div>
		<div class="textarea_box"><textarea cols="1" rows="1" onBlur="if(this.value=='') this.value='Bericht'" onFocus="if(this.value =='Bericht' ) this.value=''"  >Bericht</textarea></div>
		<a href="#" class="color1" onClick="document.getElementById('ContactForm').submit()">Verstuur</a>
		<a href="#" class="color1" onClick="document.getElementById('ContactForm').reset()">Wissen</a>
	</div>
</form>

The forms.js script:
Code:
;(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:'/mail/MailHandler.php',
                    ownerEmail:'hvellekoop@gmail.com',
                    stripHTML:true,
                    smtpMailServer:'localhost',
                    targets:'input,textarea',
                    controls:'a[data-type=reset],a[data-type=submit]',
                    validate:true,
                    rx:{
                        ".Naam":{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:/^([^\x80-\xff\(\)<>@,;:\"\.\[\]\x00-\x20]+|\"([^\x80-\xff"\\x0d]*|\[\x00-\x7f])*\")(\.([^\x80-\xff\(\)<>@,;:\"\.\[\]\x00-\x20]+|\"([^\x80-\xff"\\x0d]*|\[\x00-\x7f])*\"))*\@([^\x80-\xff\(\)<>@,;:\"\.\[\]\x00-\x20]+|\[([^\x80-\xff\[\]\\x0d]*|\[\x00-\x7f])*\])(\.([^\x80-\xff\(\)<>@,;:\"\.\[\]\x00-\x20]+|\[([^\x80-\xff\[\]\\x0d]*|\[\x00-\x7f])*\]))*/i,target:'input'},
                        ".phone":{rx:/^\+?([0-9][[0-9]\-\+\(\) ]{5,}[0-9]$)/,target:'input'},
                        ".fax":{rx:/^\+?([0-9][[0-9]\-\+\(\) ]{5,}[0-9]$)/,target:'input'},
                        ".Bericht":{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 tmp
                        return (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($('.Naam',_.form)),
                                    email:_.getValFromLabel($('.Email',_.form)),
                                    phone:_.getValFromLabel($('.phone',_.form)),
                                    fax:_.getValFromLabel($('.fax',_.form)),
                                    state:_.getValFromLabel($('.state',_.form)),
                                    message:_.getValFromLabel($('.Bericht',_.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)
$(function(){
    $('#ContactForm').forms({
        ownerEmail:'my-emailadress@gmail.com'
    })
})

Office 2010
 
Your JS file is using jQuery for some things. Do you have the jQuery library included in your page?

If not this is most likely the reason you aren't getting anything in your PHP script.

Your form elements have no names, as such when being sent to the PHP script nameless items are not considered.

If you don't have jQuery loaded your Js is probably erroring out, and not using the ajax mechanism to send the values to your PHP form so it just defaults to the standard submit from the form and tries to send the nameless values.

If you do have jQuery loaded make sure you aren't gettign any JS errors. Firefox has a great error console for this.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Thanks Phil for your respons,

I do have JQuery loaded <script type="text/javascript" src="js/jquery-1.6.js"></script>
Also Firbug is installed, but I don't understand what to do with it.. sorry..
Would it be possible to test the script? Should I post the php script as well?


Office 2010
 
I tested out the script, and it doesn't seem to be validating anything. It runs when the page first loads, but then I can insert anything I want into the inputs and it does nothing.

Then your call:
Code:
<a href="#" class="color1" onClick="[b]document.getElementById('ContactForm').submit()[/b]">Verstuur</a>
Simply submits the form but again since your inputs have no names nothing is received by the php page.

The first thing to do is to give your inputs names.

Code:
<div class="wrapper"><input class="input" type="text" value="Naam" [COLOR=#A40000][b]name="Naam"[/b][/color] onblur="if(this.value=='') this.value='Naam'" onFocus="if(this.value =='Naam' ) this.value=''" ></div>
		<div class="wrapper"><input class="input" type="text" value="Email" [COLOR=#A40000][b]name="email"[/b][/color] onblur="if(this.value=='') this.value='Email'" onFocus="if(this.value =='Email' ) this.value=''" ></div>
		<div class="textarea_box"><textarea cols="1" rows="1" [COLOR=#A40000][b]name="Bericht"[/b][/color] onBlur="if(this.value=='') this.value='Bericht'" onFocus="if(this.value =='Bericht' ) this.value=''"  >Bericht</textarea></div>

The second part is to get a validation script that actually works. My jquery knowledge is a little limited so I can't really tell you why its not working on blur of each input, maybe someone else here can.


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
i believe the issue is that you are using a javacript event bound to an anchor to submit the form. the jQuery 'submit' event is triggered via clicking a submit button or clicking enter. It does not get captured by the javascript programmatic submit() action.

solutions:
1. change the links to buttons and get rid of the javascript.
2. expressly bind the click event on the links to the forms.js submit handler.
3. expressly bind the links to the jQuery submit event (as opposed to the native javascript)

preference is, in order, 1,3,2. unless you insist on using styled links, in which case 3 is the best.

not tested this but something like the following should work

Code:
$(document).ready(function(){
    $('#ContactForm')
    		.forms({
        ownerEmail:'my-emailadress@gmail.com'
    })
    		.find('a:contains["Verstuur"]').on('click', function(e){
    			$(this).closest('form').trigger('submit');
    			})
    		.find('a:contains["Wissen"]').on('click', function(e){
    			$(this).closest('form').trigger('reset');
    			});
});

 
Ok guys, thanks, I will try to implement your suggestions.
Thanks for supporting!

Office 2010
 
remember too to remove the javascript from your form

Code:
<form id="ContactForm" method="post" action="mail/MailHandler.php">
	<div>
		<div class="wrapper"><input class="input" type="text" value="Naam"  onblur="if(this.value=='') this.value='Naam'" onFocus="if(this.value =='Naam' ) this.value=''" ></div>
		<div class="wrapper"><input class="input" type="text" value="Email"  onblur="if(this.value=='') this.value='Email'" onFocus="if(this.value =='Email' ) this.value=''" ></div>
		<div class="textarea_box"><textarea cols="1" rows="1" onBlur="if(this.value=='') this.value='Bericht'" onFocus="if(this.value =='Bericht' ) this.value=''"  >Bericht</textarea></div>
		<a href="#" class="color1">Verstuur</a>
		<a href="#" class="color1">Wissen</a>
	</div>
</form>

it would be better too to move all your inline javascript validation requirements to the validation library.

i have not checked the forms.js other than to make the bindings work for you.
 
sorry. some earlier errors. :contains() takes round brackets and not square brackets

Code:
$(document).ready(function(){
    $('#ContactForm')
    		.forms({
        ownerEmail:'my-emailadress@gmail.com'
    })
    		.find('a:contains("Verstuur")').on('click', function(e){
    			$(this).closest('form').trigger('submit');
    			})
    		.find('a:contains("Wissen")').on('click', function(e){
    			$(this).closest('form').trigger('reset');
    			});
});
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top