Jump to content
Larry Ullman's Book Forums

Forms In Javascript Or Php?


Recommended Posts

Hi

I have used Javascript and PHP for several months now, but I have yet to use a framework. I'm still a bit unsure about which is the best method for creating my forms. I usually put form validation in both the Javascript and PHP. I'm planning to learn a new framework now, and buy one of Larrys books. Either the Javascript or the Yii book. So the answer to this question will also help guide me towards the right book.

 

All the PHP frameworks have some method of creating forms. There is a Yii example at http://www.yiiframework.com/doc/guide/1.1/en/form.view

A form can also be generated using Javascript, and the various Javascript frameworks also have their own ways of generating forms. There is a Knockout.js example at http://knockoutjs.com/examples/contactsEditor.html

Of course you would need to add some PHP to this to have it store the contacts in a database.

 

Which method is "best practice"? Javascript seems to provide more flexibility for trendy display techniques, but it would seem to me that PHP would integrate better with the back end database.

How do you decide upon the code for generating your forms?

Thanks

Diarmuid

Link to comment
Share on other sites

I think it's important to differentiate between generating forms and validating form data.

 

For validating form data, PHP should always perform the final and most thorough validation simply for the fact that it's a server-side language that cannot be viewed or accessed like JS can (because it's client-side). However, using JS in addition to PHP for basic form validation is a good idea as well. By doing so, you can catch most obvious and accidental mistakes right away with JS, before the form is even submitted, making the responsiveness of the form much higher and save on unnecessary server calls.

 

As for generating the form, it really doesn't matter. The important thing to understand is that at the end of the day, all forms are made up of HTML, which both PHP and JS can dynamically create in the same fashion. With JS only, you can of course add some nice little touches using event handling and the like, but keep in mind that users can disable JS at any time in their browser, so you should never depend on only JS to do something critical on your site, or some users may be left out.

For that reason, I pretty much always use only PHP to code the HTML used for generating a form. On top of the basic HTML, I may use JS to spice things up a bit, but again, I never use JS for anything essential.

  • Upvote 2
Link to comment
Share on other sites

Agree with your point about the validation, thats actually what I do at the moment.

Good point about disabling Javascript.

With regards to your comment about using "JS to spice things up" - how do you go about this? If you're using PHP to generate the form, would you still use a JS framework as well?

Thanks

Diarmuid

Link to comment
Share on other sites

Hi, Awesomo.

 

HartleySan gave a fantastic answer; really couldn't have said it better myself.

 

With regard to your follow-up question, I don't think you would need a js framework to use client-side form validation.  There is a great example in Larry's current js book (chapter 10, to be precise) about forms; it uses regular expressions and js.

  • Upvote 1
Link to comment
Share on other sites

I would also recommend using HTML5 with something like modernizr for non-supporting browsers. HTML5 lets you specify an input field as required and more input types are catered for such as num, email, tel and url. These additions automatically do some validation on the client side and whilst you need to provide back-up for earlier browsers, it speeds things up for users on modern browsers.

Link to comment
Share on other sites

To spice it up, you don't necessarily need a JS library you could just use hand coded JS to find out whether JS in enabled firstly then things like does the username meet requirements (i.e only letters and numbers). If not it can then be used to change the display of the form such as an error class that changes the input box to red to highlight that there is an error. 

  • Upvote 1
Link to comment
Share on other sites

Awesomo, to give you a concrete example, I'm going to use Jonathon's example above because I think it's a good example.

First off, you'll want to attach a JS event handler to the form so that when the form is submitted, JS intercepts the form submission and allows you to do whatever you need to before the form is actually submitted.

This can be accomplished as follows:

 

document.forms[0].onsubmit = function () {
  
  return false;
  
};

 

On any HTML page that contains at least one form, JS provides you with the forms array, which is a property of the document object. forms[0] always applies to the first form on the page. You can adjust the array index as need be.

The return false statement actually stops the form from being submitted. (Don't worry though, as we'll actually force the form to be submitted in a second, assuming everything is okay.)

 

Next, let's imagine that we have a user name text input that must be only letters and numbers, as Jonathon said. Here's a simple JS regex we can write to test for that:

 

document.forms[0].onsubmit = function () {
  
  if (/^[A-Za-z0-9]+$/.test(this.elements[0].value)) {
  
  }
  
  return false;
  
};

 

The above if statement tests that the user name text input contains only letters (either uppercase or lowercase) and numbers (and is not an empty string). I should note that I make several assumptions with this code:

The user name text input is the first input in the form. This can be seen by the this.elements[0] in the if statement. In this case, this refers to the form object we're interested in, and elements is an array attached to all JS form objects that allows you to access all the inputs items in the form. Naturally, elements[0] refers to the first element in the form. If you'd rather check the user name text input by ID (assuming the ID is "username"), you can replace this.elements[0] with document.getElementById('username'). The value property at the end will give you the actual string entered into the text input object.

 

If the above if statement evaluates to true, then we can assume that the user name does in fact only contain letters and numbers. That being the case, we should then submit the form normally.

However, if the if statement returns false, then we should change the border of the user name text input to red.

The following code will do just that:

 

document.forms[0].onsubmit = function () {
  
  if (/^[A-Za-z0-9]+$/.test(this.elements[0].value)) {
    
    this.submit();
    
  } else {
    
    this.elements[0].style.border = '#F00 solid 2px';
    
  }
  
  return false;
  
};

 

As before, this refers to the form object in question. this.submit() will actually submit the form as if JS never intercepted the form submit request in the first place.

If the if statement fails, then we use this.elements[0] (or document.getElementById('username'), if you want) to reference the user name text input object, and then change the border to a 2-pixel red border.

 

That's the basic concept to simple JS form validation built on top of standard PHP form validation.

One of the keys to this method is that you only submit the form when everything is okay.

And naturally, the concepts above can be rinsed and repeated as many times as necessary to validate all your form input.

I hope that helps.
  • Upvote 3
Link to comment
Share on other sites

I would also recommend using HTML5 with something like modernizr for non-supporting browsers. HTML5 lets you specify an input field as required and more input types are catered for such as num, email, tel and url. These additions automatically do some validation on the client side and whilst you need to provide back-up for earlier browsers, it speeds things up for users on modern browsers.

 

Good point. I've seen that Symfony actually can include HTML5 validation when it generates forms. Other frameworks probably do something similar. See http://symfony.com/doc/current/book/forms.html

Link to comment
Share on other sites

  • 2 months later...

JavaScript serves many purposes, but as you said, the main purpose is to add interactively to a site. Specifically, JS is usually used for the following two reasons (which often overlap):

1) Respond to user input.

2) Dynamically change the appearance/content of a page without reloading the page.

 

Nowadays though, in addition to the above, JS has a number of APIs that allow you to do things on the web that you absolutely cannot do in any other web language. Some examples are:

- 2D/3D canvas

- WebRTC (for peer-to-peer connections for video chatting, etc.)

- Socket connections

 

Hope that helps.

Link to comment
Share on other sites

 Share

×
×
  • Create New...