Can a JavaScript file tell what URL requested itself?

I've been working on a project recently where I'm appending the current date to the end of script files so that they won't be cached.

I'm surrounding the code with lots of Unit Tests and I was trying to figure out the best way I could test that the script was actually loaded with the appended timestamp.

How could a JavaScript file tell what URL requested itself? Could the script know what URL make itself load?

Initially I was thinking location.href, but that ends up being the URL of the page the script was loaded on, not the script URL itself. Someone else suggested document.referrer, but that turns out to be the URL that referred the current page.

After a little time passed and several tweets passed by my stream, the correct answer flowed by...

Thanks to @cowboy @InfinitiesLoop @ashitvora for the answer and it is sooooo cleaver!

var scripts = document.getElementsByTagName( "script" );
var lastScript = scripts[scripts.length - 1];
alert( lastScript.src );

Since the script files execute in order, if you grab the scripts on the document while you are executing, then the last script listed should be the one you are currently in!

This question has been asked on stackoverflow as well ;)

As it turns out, the above technique only works for pages that have the

Read More »

I work for appendTo - The jQuery Company

appendToLogoAs you may or may not seen on Twitter the last 3 weeks or so, I accepted an offer to work with appendTo, LLC - The Company Dedicated to jQuery where I will be doing JavaScript Consulting as well as other activities.

I first met the CEO (Mike Hostetler) and President (Jonathan Sharp) of appendTo back in January while I was at the launch of jQuery 1.4 in Washington DC.

After the unfortunate turn of events at my last job (raided by the FBI & IRS), I was forced to look for a new job opportunity.

One of the first places I thought of working for was appendTo. After several weeks of talks everything worked out and now I am an official employee!

Since I’ve started I’ve done some writing, did an architectural review of a client’s code, and most recently I’ve been diving deep in developing a JavaScript and jQuery library.

I am really excited about this opportunity. The group of people that I work alongside are top notch! I find it impressive that appendTo has 5 official jQuery Team members working for them.

It looks like I’ll be able to attend the Boston jQuery Conference this coming October 16-17, 2010. I hope to see you there! Sign up while tickets last.

<blockquote>By the way, thank all of you who sent me job leads, contacting me about working with you, or tweeted on my behalf while I was looking for a job. I appreciate all your efforts!</blockquote>

Read More »

@ElijahManor is Looking for a jQuery &| ASP.NET MVC Job

If you haven’t heard already, I am looking for a new job opportunity… and yes, I realize the title of this blog is speaking in the 3rd person ;)

I am primarily looking for a full-time position where I can either work in a Nashville office or work remotely from Nashville.

I am a Microsoft MVP of ASP.NET and a member of the ASPInsiders group.

I specialize in developing with jQuery and ASP.NET MVC. I tend to focus on the UI only (everything up to the web service call to the middle tier).

I enjoy blogging, writing technical articles, speaking, and playing with the latest and greatest web development tools and libraries.

You can find my resume on my LinkedIn profile.

I look forward to hearing more about your company & the positions that you have available.

Please contact me either through LinkedIn, Twitter (@elijahmanor), or my Contact page.

Read More »

jQuery jqGrid Plugin: Add, Edit, Delete with ASP.NET MVC

 

Introduction

There are a lot of articles out there that show you how to integrate with the jQuery jqGrid Plugin from a listing, paging, sorting approach, but I haven’t seen many that show the integration with the add/edit/delete features that jqGrid offers.

It turns out that it isn’t very difficult to do, but it took quite a bit of digging in the jqGrid API documentation for me to find all the things I needed.

The following article will show how to customize the add/edit/delete modal experience inside of the jqGrid with ASP.NET MVC.

Contact ViewModel

First, you start off with your ViewModel. In this case the following is really bare bones. I haven’t annotated the properties with metadata because I actually do that manually in the jqGrid columns. That isn’t optimal, but it would be nice to have these automatically mapped. That sounds like another blog post ;)

public class ContactViewModel
{
public System.Guid ContactId { get; set; }

public string Name { get; set; }

public string Email { get; set; }

public string PhoneNumber { get; set; }

public DateTime DateOfBirth { get; set; }

public bool IsMarried { get; set; }
}

Contact View

The following code setups up the jqGrid to support add, edit, and delete.

The first function you’ll see is a custom validator that checks to see if the phone number has a length of 14. Yes, it isn’t bullet-proof validation by any stretch of the imagination, but its more of an example of what can be done.

Next you’ll see the updateDialog object literal defining the look and behavior of the add, edit, and delete dialog windows. The main property to define is the URL where the AJAX requests will post the data. You can also control whether the dialog closes immediately, if it’s a modal dialog, etc…

The next important thing to notice is the “key: true” property of the ContactId column. If you don’t set this property then the POST for the delete command  only send the relative ID that jqGrid generates, not the ContactId that you need. So, this is important ;)

Note: You’ll see some code below setting global properties for the jqGrid such as the title of the dialogs, buttons, etc. If you don’t do this then you’ll get generic titles. I figured these customizations made the user experience a little nicer, but things will work just find without them.

function isValidPhone(value, name) {
console.log('isValidPhone');
var errorMessage = name + ': Invalid Format';
var success = value.length === 14;
return [success, success ? '' : errorMessage];
}

$(document).ready(function () {
var updateDialog = {
url: '<%= Url.Action("Update", "Contact") %>'
, closeAfterAdd: true
, closeAfterEdit: true
, afterShowForm: function (formId) {
$("#PhoneNumber").mask("(999) 999-9999");
$("#DateOfBirth").datepicker();
}
, afterclickPgButtons: function (whichbutton, formid, rowid) {
$("#PhoneNumber").mask("(999) 999-9999");
}
, modal: true
, width: "400"
};

$.jgrid.nav.addtext = "Add";
$.jgrid.nav.edittext = "Edit";
$.jgrid.nav.deltext = "Delete";
$.jgrid.edit.addCaption = "Add Contact";
$.jgrid.edit.editCaption = "Edit Contact";
$.jgrid.del.caption = "Delete Contact";
$.jgrid.del.msg = "Delete selected Contact?";

$("#list").jqGrid({
url: '<%= Url.Action("List", "Contact") %>',
datatype: 'json',
mtype: 'GET',
colNames: ['ContactId', 'Name', 'Date of Birth', 'E-mail', 'Phone Number', 'Married'],
colModel: [
{ name: 'ContactId', index: 'ContactId', width: 40, align: 'left', key: true, editable: true, editrules: { edithidden: false }, hidedlg: true, hidden: true },
{ name: 'Name', index: 'Name', width: 300, align: 'left', editable: true, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
{ name: 'DateOfBirth', index: 'DateOfBirth', width: 200, align: 'left', formatter: 'date', datefmt: 'm/d/Y', editable: true, edittype: 'text', editrules: { required: true, date: true }, formoptions: { elmsuffix: ' *'} },
{ name: 'Email', index: 'Email', width: 200, align: 'left', formatter: 'mail', editable: true, edittype: 'text', editrules: { required: true, email: true }, formoptions: { elmsuffix: ' *'} },
{ name: 'PhoneNumber', index: 'PhoneNumber', width: 200, align: 'left', editable: true, edittype: 'text', editrules: { required: true, custom: true, custom_func: isValidPhone }, formoptions: { elmsuffix: ' *'} },
{ name: 'IsMarried', index: 'IsMarried', width: 200, align: 'left', editable: true, edittype: 'checkbox', editoptions: { value: "True:False" }, editrules: { required: true}}],
pager: $('#listPager'),
rowNum: 1000,
rowList: [1000],
sortname: 'ContactId',
sortorder: "desc",
viewrecords: true,
imgpath: '/Content/Themes/Redmond/Images',
caption: 'Contact List',
autowidth: true,
ondblClickRow: function (rowid, iRow, iCol, e) {
$("#list").editGridRow(rowid, prmGridDialog);
}
}).navGrid('#listPager',
{
edit: true, add: true, del: true, search: false, refresh: true
},
updateDialog,
updateDialog,
updateDialog
);
});

Contact Controller Update Action

The add/update/delete feature takes one URL where you can change the logic based on the operation type. The MVC Modal Binder will map the fields into your ViewModel in most cases. The exception is the “id” that is passed on the delete operation, but there is a way to get around that later in this post ;)

public ActionResult Update(ContactViewModel viewModel, FormCollection formCollection)
{
var operation = formCollection["oper"];
if (operation.Equals("add") || operation.Equals("edit"))
{
repository.SaveOrUpdate(new ContactViewModel
{
ContactId = viewModel.ContactId,
DateOfBirth = viewModel.DateOfBirth,
Email = viewModel.Email,
IsMarried = viewModel.IsMarried,
Name = viewModel.Name,
PhoneNumber = viewModel.PhoneNumber
});
}
else if (operation.Equals("del"))
{
repository.Delete(new ContactViewModel
{
ContactId = new Guid(formCollection["id"])
});
}

return Content(repository.HasErrors.ToString().ToLower());
}

What About Using Complex Keys?

Instead of having ContactId (“key: true”) as your key to delete, you might have a more complex key to identify which item to delete. As it turns out, you can bind to the onclickSubmit event of the add/edit/delete dialog and change what data is POST’ed to the controller.

A nice side effect of this is that you name your property such that the MVC Modal Binder works.

Updated Dialog Object Literal

var updateDialog = {
url: '<%= Url.Action("Update", "Contact") %>'
, closeAfterAdd: true
, closeAfterEdit: true
, afterShowForm: function (formId) {
$("#PhoneNumber").mask("(999) 999-9999");
$("#DateOfBirth").datepicker();
}
, afterclickPgButtons: function (whichbutton, formid, rowid) {
$("#PhoneNumber").mask("(999) 999-9999");
}
, modal: true
, onclickSubmit: function (params) {
var ajaxData = {};

var list = $("#list");
var selectedRow = list.getGridParam("selrow");
rowData = list.getRowData(selectedRow);
ajaxData = { ContactId: rowData.ContactId };

return ajaxData;
}
, width: "400"
};

Updated Contact Controller Update Action

public ActionResult Update(ContactViewModel viewModel, FormCollection formCollection)
{
var operation = formCollection["oper"];
if (operation.Equals("add") || operation.Equals("edit"))
{
repository.SaveOrUpdate(new ContactViewModel
{
ContactId = viewModel.ContactId,
DateOfBirth = viewModel.DateOfBirth,
Email = viewModel.Email,
IsMarried = viewModel.IsMarried,
Name = viewModel.Name,
PhoneNumber = viewModel.PhoneNumber
});
}
else if (operation.Equals("del"))
{
repository.Delete(new ContactViewModel
{
ContactId = viewModel.ContactId
});
}

return Content(repository.HasErrors.ToString().ToLower());
}

Conclusion

I hope you found the above article of some use in your everyday coding. The jqGrid also provides an inline editing feature similar to what you might experience in an Excel grid. You might look into that if you are interested.

Please give me your feedback. Thanks!

Download Source Code



Read More »

Filling Address Fields using HTML5 Geolocation and jQuery

I saw an interesting tweet by Remy Sharp (@rem) the other day that sparked my interest.

47b091843184dc342cdd0f26c4943ed0

So, I proceeded to research the Geolocation API and look up various web services that allowed me to utilize JSONP requests from jQuery.

Here is some pseudocode to describe what I came up with…


if (Your browser supports the GeoLocation API) {
if (Geolocation data contains address) {
Use address to populate form (Firefox)
} else {
Use Long/Lat to get address from web service & populate form (Chrome)
}
} else {
Use IP address to get address from web service & populate form (IE)
}

 

cooltext439925164

Note: You may notice depending on the browser not all of the fields are being filled out. This is because of the web services that I am utilizing are lacking one or more fields or vary depending on your location. If I find a better web service then I’ll update the script.

Read More »