Send Email Using jQuery and Web.API (Part 1)

Every site no matter how small contains the ability to submit emails. These emails can be for contacting, notifying, fulfilling or subscribing to something. Since the world of AJAX, jquery, and other frameworks have been adopted by “main” stream companies, it seems archaic for a site to request the information and then to hit a submit button and for the complete page to be sent off to the server for processing. In fact, I think that all sites that have emailing of something should be required to use state-less, a sync processing. In this exercise I am going to show you how simple it is to be able to create a standing library that can be modified quickly to fit just about any email requirement. Once this is implemented you will be able to alter this library and have a real professionally done email submitting process.

I am going to use Microsoft .NET framework but php would be called the same way. The only difference in on the server-side processing. I am going to use web forms instead of MVC but modifying the server side for MVC would not be difficult. Part 1 will be the client side of the form. This will also use some small validation checks as well, which you can implement fairly complex rules. Let’s get started.

1. Create a Visual Studio 2012 new blank web site.
2. Create a web form that will hold your message fields. (See code Below)

<div id="email" style="padding-top:40px">
	<div style="float:left;width:375px">
		<label>Email *:</label><br />
		<input id="txtEmail" type="text" />
		<br />
		<label>Name *:</label><br />
		<input id="txtName" type="text" />
		<br />
		<label>Company Name:</label><br />
		<input id="txtCompanyName" type="text" />
		<br />
		<label>Address:</label><br />
		<input id="txtAddress" type="text" />
		<br />
		<label>City:</label><br />
		<input id="txtCity" type="text" />
		<br />
		<label>State / Zip Code:</label><br />
		<input id="txtStateZip" type="text"/>
		<br />
		<label>Phone Number:</label><br />
		<input id="txtPhone" type="text" />
	</div>
	<div style="float:right; width:375px">
		<label>Subject</label><br />
		<input id="txtSubject" type="text" />
		<br />
		<label>Message:</label><br />
		<textarea id="txtMsg" cols="20" rows="6" ></textarea>
		<br />
		<label>Would like information about:</label><br />
		<select id="ddlInfo" >
			<option>Sales</option>
			<option>Product Support</option>
			<option>Warranty</option>
			<option>Other</option>
		</select>
		<br />
		<textarea id="txtComment" cols="20" rows="3"></textarea>
		<br />
		<div style="margin:0px auto;text-align:center" >
			<img src="/images/sendemail.jpg" id="btnSend"/>
		</div>
		<div id="SendStatus" style="color:red;text-align:center; font-size:14px"></div>
	</div>
</div>

3. Create a new javascript file and paste the code below. (It contains internal notes as to what each section does.)

//This attaches a function to the Submit Button

jQuery(document).ready(function () {
jQuery(function ($) {
	$("#btnSend").click(function () {
	$("#SendStatus").text("")
	//Sets up the loading image for ajax calls to the server
	//*********************************************************
	$.ajaxSetup({
		beforeSend: function () {
			$("#SendStatus").text("Sending Email...")
			},
		complete: function () {
			},
		success: function () { }
	});
	//*********************************************************
	//Set these to each field in the form
	var dataString = {
	Name: $("#txtName").val(),
	EmailFrom: $("#txtEmail").val(),
	CompanyName: $("#txtCompanyName").val(),
	Address: $("#txtAddress").val(),
	City: $("#txtCity").val(),
	State: $("#txtStateZip").val(),
	PhoneNumber: $("#txtPhone").val(),
	Subject: $("#txtSubject").val(),
	Message: $("#txtMsg").val(),
	Information: $("#ddlInfo option:selected").text(),
	Comment: $("#txtComment").val(),
	EmailTo:$("#txtEmailTo").val(),
	EmailToName:$("#txtEmailToName").val()
	}

	//This calls the sendemail sub
	sendEmail(dataString, function (newEmail) {
	$("#SendStatus").text("Email Sent Successfully ");
	$("#btnSubmit").unbind("click");
	//Remove Submit Button to help eliminate duplicate submissions
	$("#btnSubmit").remove();
	},

	function (errors) {
		var strErrors = "";
		$.each(errors, function (index, err) {
		strErrors += "" + err.Value + "\n";
		});
	$("#SendStatus").text(strErrors);
	}
);

//Ajax Call to the web.api
function sendEmail(dataString, success, fail) {
	$.ajax({
		url: "../api/SendEmail",
		data: JSON.stringify(dataString),
		type: "POST",
		contentType: "application/json;charset=utf-8",
		statusCode: {
			201: function (newEmail) {
				success(newEmail);
			},
			400: function (xhr) {
				var errors = JSON.parse(xhr.responseText);
				fail(errors);
			},
			404: function (xhr) {
				var errors = JSON.parse(xhr.responseText);
				fail(errors);
			}
		}
	});
}
});
})
})



Stay tuned for Part 2 which I will show you the server side code using web.api. Along with some small error validation.

Looking for quality web hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , | Posted under ASP .NET 4.0 | RSS 2.0

Author Spotlight

David Bauernschmidt

David Bauernschmidt

I live in the historical triangle of Virginia where I am married with two daughters. I have spent over 13 years working for a Fortune 500 company in the computer area. I started in VB 6.0 and by the time I ended my employment I was supervising a development team where we built many web applications. When my first daughter was born I wanted to spend more time with her so I left and became a programmer analyst for local government as well as launch my own company. Since then I have grown James River Webs into a profitable web design and application company helping small businesses create a big presence on the internet. As an employee I have created web application used by citizens and other companies. I enjoy fly fishing, and spending time with my family. I also enjoy learning new approaches and development tools when it comes to developing applications.

Leave a Reply

Your email address will not be published. Required fields are marked *


8 × = 64

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>