Monday, 20 January 2014

send form data in email javascript or php

In web development it is very normal that we create 'Contact-Us' Form . And we want to send complete form submitted data in a mail to somebody (normally to ourself ).
There are many ways to do this .
1) using javascript
2) using any server side scripting like PHP .

To understand this first of all, we need to understand concept of sendmail utilites and mail server . for sending mail , we need to have a mail server or mail client . best example for mail client is MS-outlook and mail client is "mail" command in linux .
First way -- javascript  -->
As we know javascript is client side scripting , so it need a client to send mail i.e. mail client .
Example :-
lets take a simple form .
<form action="">
Name <input type="text" name="name" />
Phone <input type="text" name="phone" /> 
<input type="submit" name="submit" value="submit"/>

This is simplest example . If we try to see what happens here , we are using javascript "mailto" function . "mailto" will trigger mail client to send mail that means , it will call you MS-Outlook (if installed and configured ) .This way is not used widely as it is client dependent way and we don't have any control here .

Second way -- server side scripting e.g. PHP -->
php will need a mail server configured to send a mail . As we are developers we can control and configure mail server by our own .
Example :-
<form action="abc.php" method="post">
Name <input type="text" name="name" />
Phone <input type="text" name="phone" /> 
<input type="submit" name="submit" value="submit"/>

$name = $_POST['name'];
$phone = $_POST['phone']; 
$to = "";
$subject = "Contact details ";
$message = "The name is  $name \n\r Contact number is $phone ";



Now this is stable and trusted code to send mails . And everyone should use this way of sending mail .

There are two ways of submitting form i.e. GET and POST . Both methods have their importances .
If we submit form using get method and then all data submitted will be append in the action page url . And we know that url have its limits so we can send only small amount of data using GET method .
While in POST method data is sent in the request body so there is no limit here to send data .
Also in GET method data is visible in th url , so it is not safe . Whenever we need to create safe application we should use POST method .
GET method is fast as everything is simply appended in the url . But in using POST method every request need to maintain data in the body . So it is lsightly time consuming method .

Both methods are useful . So we need to choose wisely according to our application taht which method we should use .

Thank you . Please ask in comments if need any clarification . Suggestions are also welcome .