I'm trying to setup a Node.js
server that will listen for a contact form request URL
and then retrieve the relevant data
from the contact form
.
The client
will basically send out a request that should look like this :
HTML :
<form>
<input type="text" class="typed" placeholder="name" name="name">
<input type="text" class="typed" placeholder="email" name="email">
<input type="text" class="typed" placeholder="subject" name="subject">
<textarea class="typed" placeholder="your enquiry.." name="enquiry"></textarea>
<input type="submit" value="submit">
</form>
JS :
$('form').submit(function ()
{
var name = $.trim($(this).find('[name="name"]').val());
var email = $.trim($(this).find('[name="email"]').val());
var subject = $.trim($(this).find('[name="subject"]').val());
var enquiry = $.trim($(this).find('textarea').val());
$.ajax({
url: "/contactform",
type:'POST',
data: {
name : name,
email: email,
subject: subject,
enquiry: enquiry
}
});
});
The browser escapes the necessary symbols and replaces the blanks with "+" and ends up sendind out something like this :
/contactform?name=some+name&email=someemail%40address.com&subject=some+email+subject&enquiry=some+enquiry
The server will receive the above request, it will escape it and then use Regex to try and retrieve the relevant data it contains, as follows :
var httpServer = http.createServer(function (request, response)
{
// escaping it doesn't actually replace the "+" does it ? Any solutions ?
var requestURL = unescape(request.url);
var name = requestURL.match(/name=([^&email=]*)/)[1]; // returns * so * which is wrong
var email = requestURL.match(/email=([^&subject=]*)/)[1]; // returns an empty string which is wrong
var subject = requestURL.match(/subject=([^&enquiry=]*)/)[1]; // returns * som * which is wrong
var enquiry = requestURL.match(/enquiry=(.*)/)[1]; // returns * some+enquiry * which is correct
}).listen(8080);
As you can read in the comments, my regex is not working properly. You can try it on your browser's console yourselves. What am I doing wrong ?
Also, as I'm new to this, is there a better format for sending out contact form data, from the client to the server? Or is the ?xxx=xxx+xxx+xxx&xxxx=xxxx+xx+xxx&....etc
format the best one since it seems to be the standard one? The browser forces the above format but I could force a different one using JS right?
I'm just thinking that the above won't work if the user happens to e.g. use &subject= somewhere in the text they type in. It's highly unlikely but still kind of annoying that there isn't a 100% reliable way of retrieving form data on the server. Or is there one ?
The above client/server side code is obviously incomplete. I'm omitting the irrelevant stuff to make it more readable..
Thanks for your help in advance.