How to Change the URL in AJAX Applications

8

"How to Change the URL in AJAX Applications" by CMSN Software Tutorials, shows you how to change the browser URL without refreshing the page. In this tutorial we are using HTML5 history API. Since HTML5 is not supported by all browsers, we are using location.hash as fallback option. For more information about How to use hash values, you can read our previous tutorial (How to create SEO friendly AJAX applications). Since this is not going to change our non Ajax based application structure, this will support SEO as well.

In this tutorial, we don't need change anything of our current application. We can use our non Ajax application as it is. When we refer following JavaScript file, it will override the click events of available hyperlinks to support Ajax based application. So if you turn off the JavaScript support from the browser, it will work without any issue. And all crawlers will index your site.
$("#ResultContainer").prepend($("<mark/>").html("Page load event fired"));
 
$(document).on("click""a"function (event) {
    /// <summary>
    ///     Assign click event for all available hyperlinks for load content via Ajax 
    /// </summary>
    event.preventDefault();
    var navigationPath = $(this).attr("href");
    loadContent(navigationPath);
    updateLocation(navigationPath);
});
onLocationChanged();
 
function loadContent(url) {
    /// <summary>
    ///     Load content from given location via Ajax request.
    /// </summary>
    /// <param name="url" type="String">Location of the new content</param>
    $.ajax({
        url: url,
        type: 'GET',
        contentType: "text/html; charset=utf-8",
        dataType: "html",
        success: function (responseData) {
            $("#ResultContainer").html($("#ResultContainer", responseData).html());
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " : " + errorThrown);
        }
    });
}
 
function updateLocation(relatedPath) {
    /// <summary>
    ///     Update the URL for new content without reloading the page
    /// </summary>
    /// <param name="relatedPath" type="String">Path foe updating location</param>
    if ("pushState" in history) {
        // use window.history.pushState if it support by the browser
        var currentPath = relatedPath ? { navigationPath: relatedPath} : "";
        window.history.pushState(currentPath, document.title, "/" + relatedPath);
    } else {
        // use hash as fallback option
        window.location.hash = relatedPath;
    }
}
 
function onLocationChanged() {
    /// <summary>
    ///     Register event handler for location change. 
    ///     This is used to load content when browser back button pressed
    /// </summary>
    if ("pushState" in history) {
        $(window).on("popstate"function (e) {
            var state = e.originalEvent.state;
            if (state && state.navigationPath) {
                var contentPath = state.navigationPath;
                loadContent(contentPath);
            }
        });
    }
    else {
        $(window).on('hashchange'function () {
            $href = $(window.location).attr("hash");
            loadContent($href.replace("#"""));
        });
    }
}

First line of the above file will indicate when full page reload is fired. It is not required for the actual application. Next step is binding a click event for matching hyperlinks.That event prevents the default navigation and load that content via Ajax request. It will convert our non Ajax application to Ajax based application. We can change the url for above loaded content by using history.pushState. But since it is not supported by all browsers, we have to use location.hash as a fallback option. Then we can use onpopstate event for the back button functionality and onhashchange can be use as fallback option

Nothing new in following code. This is just a sample data providing classes to support the application.
//-----------------------------------------------------------------------
// <copyright file="CarStore.cs" company="CMSN Software">
//    Copyright © 2010  CMSN Software
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see http://www.gnu.org/licenses.
// </copyright>
//-----------------------------------------------------------------------
 
namespace CMSNSoftwareTutorials
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
 
    /// <summary>
    /// containing all car details
    /// </summary>
    public static class CarStore
    {
        /// <summary>
        /// Populates the car details.
        /// </summary>
        /// <returns>car details</returns>
        public static ReadOnlyCollection<Car> AllCars()
        {
            List<Car> cars = new List<Car>();
            cars.Add(new Car { Id = 1, Make = "Audi", Model = "A4", Year = 1995, Doors = 5, Color = "Red", Price = 2995f });
            cars.Add(new Car { Id = 2, Make = "Ford", Model = "Focus", Year = 2002, Doors = 5, Color = "Black", Price = 3250f });
            cars.Add(new Car { Id = 3, Make = "BMW", Model = "5 Series", Year = 2006, Doors = 4, Color = "Grey", Price = 24950f });
            cars.Add(new Car { Id = 4, Make = "Renault", Model = "Laguna", Year = 2000, Doors = 5, Color = "Red", Price = 3995f });
            cars.Add(new Car { Id = 5, Make = "Toyota", Model = "Previa", Year = 1998, Doors = 5, Color = "Green", Price = 2695f });
            cars.Add(new Car { Id = 6, Make = "Mini", Model = "Cooper", Year = 2005, Doors = 2, Color = "Grey", Price = 9850f });
            cars.Add(new Car { Id = 7, Make = "Mazda", Model = "MX 5", Year = 2003, Doors = 2, Color = "Silver", Price = 6995f });
            cars.Add(new Car { Id = 8, Make = "Ford", Model = "Fiesta", Year = 2004, Doors = 3, Color = "Red", Price = 3759f });
            cars.Add(new Car { Id = 9, Make = "Honda", Model = "Accord", Year = 1997, Doors = 4, Color = "Silver", Price = 1995f });
            return new ReadOnlyCollection<Car>(cars);
        }
 
        /// <summary>
        /// Cars the information.
        /// </summary>
        /// <param name="id">The id of the selected car</param>
        /// <returns>selected car details</returns>
        public static Car CarInformation(int id)
        {
            ReadOnlyCollection<Car> allCars = CarStore.AllCars();
            Car carDetail = (from car in allCars
                             where car.Id == id
                             select car).FirstOrDefault();
            return carDetail;
        }
    }
}

This is a custom class to keep sample data.

//-----------------------------------------------------------------------
// <copyright file="Car.cs" company="CMSN Software">
//    Copyright © 2010  CMSN Software
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see http://www.gnu.org/licenses.
// </copyright>
//-----------------------------------------------------------------------
 
namespace CMSNSoftwareTutorials
{
    /// <summary>
    /// keeps car information
    /// </summary>
    public class Car
    {
        /// <summary>
        /// Gets or sets the id of the car.
        /// </summary>
        /// <value>
        /// The id of the car.
        /// </value>
        public int Id { getset; }
 
        /// <summary>
        /// Gets or sets the make.
        /// </summary>
        /// <value>
        /// The manufacture of the car.
        /// </value>
        public string Make { getset; }
 
        /// <summary>
        /// Gets or sets the model.
        /// </summary>
        /// <value>
        /// The model of the car.
        /// </value>
        public string Model { getset; }
 
        /// <summary>
        /// Gets or sets the year.
        /// </summary>
        /// <value>
        /// The year of the car.
        /// </value>
        public int Year { getset; }
 
        /// <summary>
        /// Gets or sets the doors.
        /// </summary>
        /// <value>
        /// number of doors of the car.
        /// </value>
        public int Doors { getset; }
 
        /// <summary>
        /// Gets or sets the color.
        /// </summary>
        /// <value>
        /// The color of the car.
        /// </value>
        public string Color { getset; }
 
        /// <summary>
        /// Gets or sets the price.
        /// </summary>
        /// <value>
        /// The price.
        /// </value>
        public float Price { getset; }
    }
}

This is a custom class to keep sample data.

Download tutorial

8 comments:

Anonymous -
Good web site you have here.. It's difficult to find quality writing like yours nowadays. I truly appreciate individuals like you! Take care!!
my web site - Google seo
Anonymous -
I just like the helpful information you provide on your articles.
I will bookmark your blog and check once more right here regularly.
I'm fairly certain I'll learn many new stuff right right
here! Good luck for the next!

Here is my site: web file explorer

Post a Comment