Simple WordPress HTTP API Tutorial

This article is to show beginners how to consume a Web Service and display results on your WordPress website. I say beginner, I mean a beginner in using Web Services or  a beginner in WordPress development. I also assume you have an idea of what web services are, what a Endpoint is, what is JSON, and what are RESTFUL services, You are someone just looking for advice on how to accomplish this in a WordPress website. Some knowledge of WordPress, some basic PHP and some basic knowledge of WordPress theme development and/or WordPress plugin development are suggested. If you are a brand new WordPress user that has never written any code this might not be the article for you. A person that has written some PHP code and has knowledge of the WordPress file structure should be able to understand this article.   To start, we need to take a look at the documentation for WordPress HTTP API.

WordPress HTTP API

 

The functions below are the ones you will use to retrieve an URL. Please be aware that these functions will return a WordPress WP_Error class on failure.

* wp_remote_get() – Retrieves a URL using the GET HTTP method.
* wp_remote_post() – Retrieves a URL using the POST HTTP method.
* wp_remote_head() – Retrieves a URL using the HEAD HTTP method.
* wp_remote_request() – Retrieves a URL using either the default GET or a custom HTTP method (should be caps) that you specify.

The other helper functions deal with retrieving different parts of the response and do the testing for WP_Error for you, these make usage of the API very simple and are the preferred method for processing response objects.

* wp_remote_retrieve_body() – Retrieves just the body from the response.
* wp_remote_retrieve_header() – Gives you a single HTTP header based on name from the response.
* wp_remote_retrieve_headers() – Returns all of the HTTP headers in an array for processing.
* wp_remote_retrieve_response_code() – Gives you the number for the HTTP response. This should be 200, but could be 4xx or even 3xx on failure.
* wp_remote_retrieve_response_message() – Returns the response message based on the response code.
So in this tutorial we will be using the wp_remote_get function to make the request to the web service API. After successfully connecting and getting back our JSON data, we will then use the wp_remote_retrieve_body function to grab just the body of the request and then parse the data. Normally, in basic PHP we would be using cURL but WordPress already has everything baked into the Core so we will be using those functions.

Lets get started. First what I am going to do is to create a new template in my present theme. So jump into your present theme’s folder and create a new file, I am calling mine rest.php. So now in my theme’s main folder I have a new file called rest.php. Now I am going to create the code so my new template will show up in my theme on the front end.  I am also going to name my new template Rest. So open up your new file called rest.php and place this in your new file.

<?php
/**
 * Template Name: Rest 
 *
 */
get_header(); 
?>
    <div id="content" class="full-width" style="padding-left: 100px;">
		<h3>WP_Http</h3>
		<?php

		/* our new code will go */

		?>        
	</div>
<?php 
get_footer(); 
?>

Now remember, my theme will be different than your theme. What I did was just copy one of my themes other template files and stripped everything out of the main content area, I left my get_header, get_footer and the main content div. OK, so now I have my new template file so I will be able to see the results on the front end.  Now, I will login into the admin side of my WP website, create a new page, and then choose the new ‘Rest’ template we just created.  Be sure and Save. Go to the front end, and you should see a new page that looks like your theme with just a heading of WP_Http (That is if you copied my code above. If you did not, then your page should be empty).

wphttp-start

OK, now we are ready to get down to coding. So far we created a new template for our theme, created a new webpage and assigned this new template to the page. Displayed the new webpage in the front end that will be displaying our work.

We first need to code the Request part. I will be using the Bitbucket API.  For information on BitBucket: Bitbucket

For more information on their APIs: Bitbucket API

We will be making a call using the Bitbucket API to get the names of my repositories I have on Bitbucket.

In order to do this example, you will need an account at Bitbucket. If you are one of those developers who keeps avoiding GIT and putting your code into repositories, maybe this tutorial will give you the push to start. This tutorial will also being using Basic Authentication, so you will need to use your own username and password. I decide to use a web service that makes use of Authentication because there are less of these types of examples out there. OK, so after reading the Bitbucket API documentation, I will be using this Endpoint:  https://api.bitbucket.org/1.0/user/

Now time to start coding the request part:

<?php
$url = 'https://api.bitbucket.org/1.0/user/';

$username = '*******************';

$password = '****************';

$headers = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ) );

$request = wp_remote_get( $url, array( 'headers' => $headers ) );

if(is_wp_error($request)) {
return false;
}
    			
$body = wp_remote_retrieve_body($request);

$data = json_decode($body);


?>

this code will be placed into my template page as such:

<?php
/**
 * Template Name: Rest 
 *
 */
get_header(); 
?>
    <div id="content" class="full-width" style="padding-left: 100px;">
		<h3>WP_Http</h3>
		<?php
            $url = 'https://api.bitbucket.org/1.0/user/';
            
            $username = ‘*******************’;
            
            $password = '****************';
            
            $headers = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ) );
            
            $request = wp_remote_get( $url, array( 'headers' => $headers ) );
            
            if(is_wp_error($request)) {
            return false;
            }
            				
            $body = wp_remote_retrieve_body($request);
            
            $data = json_decode($body);
        ?>
	</div>
<?php 
get_footer(); 
?>

 

$url is the Endpoint .

$username will be your username.

$password will be your password

$headers = array( ‘Authorization’ => ‘Basic ‘ . base64_encode( “$username:$password” ) );

$headers will be an array that holds our Authentication variables.

$request = wp_remote_get( $url, array( ‘headers’ => $headers ) );

$request: here we will use the WP HTTP API function wp_remote_get() and pass in our endpoint URL and Authentication credentials.

if(is_wp_error($request)) {

return false;

}

Here we just do an error check, to make sure we have not hit an errors so far.

$body = wp_remote_retrieve_body($request);

$body: here we again use the WP HTTP API and use the wp_remote_retrieve_body function which produces only the body of the web services call response.

$data = json_decode($body);

$data: here we just use the php function json_decode so we can use the data in our php code. Time to check and see if we are successfully.

place the code below in your file after this line:        $data = json_decode($body);

This will basically dump out our json array, if we were successfully in connection to the API.

echo '<pre>';
print_r($data);
echo '</pre>';

I use the pre tags so it will print out the JSON array into a more readable formatted result.

you can just use this if you want:

print_r($data);

This section of code is just for testing. If you followed along you should see your array of information.

Now, either delete those lines of code or comment them out.

Now time to Parse our data.

if(!empty($data)) {

echo '<ul>';
foreach( $data->repositories as $repo ) { 

    	echo '<li>';
		echo $repo->name;
		echo '</li>';
	}
	echo '</ul>';
}	

First we check and make sure that our $data array is not empty. If not then we start our list declaration.  Then using a foreach loop we loop through all instances of repositories that are in the array and print out the name of each repo, When complete, we close our list and exit.

Let’s break down our foreach loop. How did we come up with those names. Well $data is our array of data, and if you ran the print_r code you see how the data is arranged. The proper name is repositories. If we start to look down our array we can see that the proper name is name.

print-r-array

 

 

So we create the foreach loop as such:

foreach( $data->repositories as $repo ) { 

    	echo '<li>';
		echo $repo->name;
		echo '</li>';
	}

So if we did everything correctly we now have a list of our Bitbucket repositories names. To see in real-time, check out the page here:

[button color=” blue” size=”small” link=”http://hyperdrivedesigns.com/wp-http/” target=””]Demo Page[/button]

 

wp-http-final

FINAL CODE:

<?php
/**
 * Template Name: Rest 
 *
 * This is the template that displays information from a web service.
 *
 * @package foundationwp
 */

get_header(); 
?>
    <div id="content" class="full-width" style="padding-left: 100px;">
		<h3>WP_Http</h3>
		<?php
			$url = 'https://api.bitbucket.org/1.0/user/';
			$username = '**************';
			$password = '**************';
			$headers = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ) );
			$request = wp_remote_get( $url, array( 'headers' => $headers ) );
			if(is_wp_error($request)) {
				return false;
			}
				
			$body = wp_remote_retrieve_body($request);

			$data = json_decode($body);
			
			if(!empty($data)) {

				echo '<ul>';
				foreach( $data->repositories as $repo ) { 

					echo '<li>';
						echo $repo->name;
					echo '</li>';
				}
				echo '</ul>';
			}			
            ?>        
    </div>
<?php get_footer(); ?>

Angular JS No BS Template for Beginners

Technology moves faster than we can keep up. Every week when I read some of my favorite web newsletters, it seems like there is a new JavaScript library. New JavaScript libraries are growing faster than my grass in the summertime. So I decide it was time to learn Angular JS. After spending many hours of reading and completing tutorials, it seems like almost every tutorial had multiple prerequisites before I could even get started. So before I could start learning Angular JS, I need to know some Node JS, Grunt, Bower, etc…  Man I just want to learn Angular. Well, after some more reading I figured out some things for beginners: You do not need to have all of these prerequisites. All you need is a web browser, editor and local development server. Since you will be coding html and javascript at first, there really is no need for a web server or local development server but I suggest a local development server anyway. Without using a server, just code your files in your editor and open up the file in a browser. This is just for beginners. The one key is in your code, you must be including the Angular JS library. After you start to learn more then you can jump into learning more advanced things and then these prerequisites will start to come into play. I even created a bare-bones Angular Template to get beginners started. This template gets rid of all the extra overhead needed for more advanced Angular development. This template is just for beginning to learn the bare basics of Angular. I call it ‘Angular JS No BS Template’. Feel free to grab it from the Github or BitBucket links below.

[button color=” blue” size=”small” link=”https://github.com/redsoxfan2499/angular-nobs” target=””]Github [/button]

[button color=” blue” size=”small” link=”https://bitbucket.org/dxladner/angular-nobs” target=””]BitBucket[/button]

Turbulence – Bootstrap WP Theme

Turbulence – Bootstrap WP Theme is now ready for purchase. Go to Brag Themes to buy Turbulence and check out the rest of the Bootstrap themes. Grab a free Bootstrap theme will you are there.

Check out our latest WordPress Theme at
turbulence.website.

This WordPress theme is based upon the Bootstrap Framework, and uses the Redux Options Framework that allows anyone to put together an Awesome Website. There are so many features so check it out at Turbulence.

Using PHP Tags In WordPress Screencast

Check out the new screen-cast titled Using PHP Tags in WordPress Screencast. Here I do a brief overview of the PHP WordPress Template Tags that are used in building WordPress themes. This screencast was created for Learnable. Learnable, is SitePoint’s sister website for learning web design/web development.

[button color=” blue” size=”small” link=”https://learnable.com/hub/play/86″ target=””]Watch Screencast[/button]

Super Simple Ajax jQuery PHP Tutorial

Here is another really super simple ajax jQuery php tutorial. This tutorial will attempt to help beginners understand the very basics of how to use Ajax to reload just a portion of your webpage instead of loading the complete page. So first what is Ajax? Ajax is an acronym which stands for Asynchronous JavaScript and XML. To put in very simple terms, it is a way for the user to request data from the server without having to reload the complete webpage. Ajax can be so smooth in displaying new changes in your webpage if done correctly. To begin, there is no one correct way to use Ajax. There are many different ways to use Ajax. Today, I will be using jQuery  ajax() function to request a PHP file.

OK. When I first started to learn Ajax and I would Google Ajax tutorial and from the results, I quickly realized that there are many different way to use Ajax. Can I say CONFUSION? Personally, i think that the jQuery ajax() function is one of the easiest to learn and use. There will be a link at the end of the tutorial for all of the source code. So you can follow along and copy the code or just download the source code.

Step 1. I am going to create a simple index.php file to markup our main webpage. Just a simple HTML 5 Document. Notice in the head of the document I am making a call to the jquery version which is hosted by jQuery. We need to make a call to the jQuery library in order to get access to the jQuery ajax function and to allow the jQuery code we write to run. You can write jQuery code but you need to either make a call to the jQuery library that is hosted on a CDN(Content Delivery Network) or download a copy of the jQuery library and place it in your website folder, usually in a folder called js or jscript. There are many different CDNs out there that host files for you to use.

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

Now I created a container in the body, then a H1 tag for a nice title. Next is the div which I gave an id of date-div. This is the div that will display the data from the php file that we will call in the jQuery ajax() function. So right now it is empty but will dynamically be changed upon a jQuery event. For the event, I created a button and attached an onclick function which will then call the getDateTime() function (we will create this function in the next step). Lastly, is the button which I attached the onclick event to call the getDateTime() function. So when the page loads the div will be empty so click the button and the jquery onclick event will call the getDateTime function which uses Ajax to request the PHP file that generates the current date and time in the American Central Timezone.
OK, here is the starting code for the index.php file:

<!doctype html>
<html>
    <head>
		<meta charset="utf-8" />
		<title>Super Simple Ajax jQuery PHP Tutorial</title>
		<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        </head>
    <body>
		<div id="container">
			<h1>Ajax jQuery PHP Tutorial</h1>
			What is the current time and date in Central Time Zone:<br />
				<div id="date-div">
					<!-- this is where the ajax file call wiil be displayed in web browser -->
				</div>
				<br/>
			<input type="button" class="btn-primary" value="Get Date & Time" onclick="getDateTime();" />
		</div>
	</body>
</html>

Step 2. Being a web developer and designer, I always want to make the examples look pretty cool with some css styles and not just plain white background and black text. So lets get styling! For simplicity sake, the norm would be to create a css folder and then a css file and then call the css file from the index.php file. Since this is a very simple tutorial, I am going to place the css styles in the head of the index.php file. First lets get rid of that plain white background and black text and H1:

body {
    background: #ecf0f1;
	color: #2c3e50;
}
h1 {
	color: #2c3e50;
}

Next, lets give our container a width and center it on the page along with the date-div and its styles:

#container {
    margin: 0 auto;
	width: 400px;
}
#date-div {
	width: 400px;
	height: 250px;
	border: 3px solid #2c3e50;
	margin: 0 auto;
	margin-top: 20px;
}

Lastly, lets do not forget our button and our paragraph tags. Stop The Clock! Where did the paragraph tags come from. This tags will be in the PHP file which we have yet to get to. So don’t worry. You will see them in the PHP file when we code that file. I gave the paragraph tags a class called pdate.

.pdate {
    color: #2c3e50;
	font-size: 16px;
	font-weight: bold;
	margin-left: 10px;
}
.btn-primary {
	background-color: #428bca;
	border-color: #357ebd;
	color: #fff;
	cursor: pointer;
	border-radius: 4px;
	display: inline-block;
	font-size: 16px;
	font-weight: 400;
	padding: 6px 12px;
	text-align: center;
	vertical-align: middle;
	white-space: nowrap;
}

OK. Enough styling. Lets get to this PHP file.

Step 3. Again keeping this as simple as possible, we will create a PHP file that will be using the PHP date function and with proper formatting we will display the date on one line and the time on the another line. I am calling this file: ajax.php. There is no AJAX code in this file, just PHP code so do not let the name confuse you. First I am using the PHP date_default_timezone_set function to set the timezone for the file. Next line, I am echoing out, or printing out the paragraph tags set with a class of pdate. HEY, there are those paragraph pdate tags we styled in the previous step. Then echo out a blank line for some spacing and then last line echo out the paragraph pdate tag again with the PHP date function using some different formatting to get the time. Here is a link to the PHP date function to research how to use the function and how to format it to the results you want.OK. Lets see the code now:

<?php
date_default_timezone_set('America/Chicago');
echo '<p class="pdate">The Date is ' . date("m/d/y") .' .</p>';
echo '<br/>';
echo '<p class="pdate">The Time is ' . date('g:i:s A') . ' .</p>';

That is it for the php file.

Step 4. Now it is time for the main event. Lets write our jQuery code using the ajax function to request the ajax.php file which will dynamically display the date and time in our date-div upon the user clicking the button. Again for simplicity sake, I will also placed this javascript code in the head of our index.php file. So I will show you the code and then try to explain it as beast as I can: And the survey says:

function getDateTime() {
    var request = $.ajax({
		url: "ajax.php",
		type: "GET",			
		dataType: "html"
	});

	request.done(function(msg) {
		$("#date-div").html(msg);			
	});
}

Lets break it down. We first name our function that will hold our ajax request. We call the function getDateTime(). This is the function that gets called when a user clicks the button on our index.php page. Inside the function, we create a variable called request which holds our ajax request. Then we start the jQuery ajax function, inside this function we have some parameters that we must give values to: url: this is the url for the file that we want to request, this could also be a file on another server, different folder, etc. Next is the type of request, we are using the GET request, and lastly is the dataType which will be returned as html. There are many more possible parameters. So here is a link to the jQuery Ajax function API documentation for more research. The last bit of code is when the request is done run the function msg which then displays the data from our ajax.php file and displays the date and time on the date-div. Click the button again and again and watch as just the time line will be changed inside our date-div and NOT the whole page reloading.

OK. Quick Summary. We have an index.php page which has our html 5 document code, including a date-div which will display our data, a button that will trigger our ajax function, our css styles and the jquery code that holds out ajax request. Our second file is a PHP file called ajax.php which uses the php date function to get the date and time in the American Central timezone. So when a user clicks the button, the button calls the getDateTime jQuery function we wrote which contains out ajax request, the ajax request, requests the our PHP file, gets the data from the PHP file and then displays the data in our date-div without reloading the whole page. I hope this tutorial helps someone just learning Ajax. Please feel free to leave any comments.

Here is the full code displayed:

index.php file

<!doctype html>
<html>
    <head>
		<meta charset="utf-8" />
		<title>Super Simple Ajax jQuery PHP Tutorial</title>
		<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
		<style type="text/css">

			body {
				background: #ecf0f1;
				color: #2c3e50;
			}
			h1 {
				color: #2c3e50;
			}
			#container {
				margin: 0 auto;
				width: 400px;
			}
			#date-div {
				width: 400px;
				height: 250px;
				border: 3px solid #2c3e50;
				margin: 0 auto;
				margin-top: 20px;
			}
			.pdate {
				color: #2c3e50;
				font-size: 16px;
				font-weight: bold;
				margin-left: 10px;
			}
			.btn-primary {
				background-color: #428bca;
				border-color: #357ebd;
				color: #fff;
				cursor: pointer;
				border-radius: 4px;
				display: inline-block;
				font-size: 16px;
				font-weight: 400;
				padding: 6px 12px;
				text-align: center;
				vertical-align: middle;
				white-space: nowrap;
			}
		</style>
		<script>
	
	function getDateTime() {
		var request = $.ajax({
			url: "ajax.php",
			type: "GET",			
			dataType: "html"
		});

		request.done(function(msg) {
			$("#date-div").html(msg);			
		});

	}
</script>
	</head>
	<body>
		<div id="container">
			<h1>Ajax jQuery PHP Tutorial</h1>
			What is the current time and date in Central Time Zone:<br />
				<div id="date-div">
					<!-- this is where the ajax file call wiil be displayed in web browser -->
				</div>
				<br/>
			<input type="button" class="btn-primary" value="Get Date & Time" onclick="getDateTime();" />
		</div>
	</body>
</html>

ajax.php file

<?php
date_default_timezone_set('America/Chicago');
echo '<p class="pdate">The Date is ' . date("m/d/y") .' .</p>';
echo '<br/>';
echo '<p class="pdate">The Time is ' . date('g:i:s A') . ' .</p>';

[button color=” blue” size=”small” link=”https://s3.amazonaws.com/hyperdrive.designs.tutorialfiles/ajax-tutorial.zip” target=””]Zipped Demo Source Files[/button]

Google Calendar Link Plugin Released

Finally! Google Calendar Link Plugin Released!

Another Small Simple WordPress Plugin: Google Calendar Link Plugin is now ready for download. To see the plugin in action and to get more information just go under the WordPress Plugins menu and Click on Google Calendar Link Plugin. In order to download the plugin, just register at our website and then go to the Plugins Download Page. From this page you can download any of our Small Simple WordPress Plugins.

Comparing Dates in PHP

If you are a web developer sometimes we have to know multiple languages. At my job, I have to know PHP, ASP.NET, JavaScript, jQuery, HTML, CSS, SQL. You get the point. Even though programming logic is pretty similar across the board, the actual syntax of the languages are different. For example, in PHP you can declare a variable as such:

$carModel = 'Nova';

In ASP.NET,to declare the same variable we have to assign a data type:

string carModel = 'Nova';

In JavaScript, to declare the same variable:

var carModel = 'Nova';

So you can see that the logic is pretty much the same, just the syntax is different. So let us take a look at comparing dates in PHP. Dealing with Dates in all of the different languages are the same. So when I had to do some PHP coding for a WordPress plugin dealing with dates, I had to reference the PHP website. So whenever I come across issues that I have to spend time to research, I try to write a post and pass along my findings. Hopefully, this will save some people some time. I do not want to offend daily PHP developers. This guys that work with PHP on a daily basis can write this code in seconds with their eyes closed. But a lot of web developers, like me, have to know multiple languages. So here is how to work with dates in PHP and deal with comparing dates.

So first I had to get the current date, using PHP’s date function:

$todaysDate = date("m/d/y");

What this does is gets today’s date and formats it as such (01/31/2014). You can format the date in many different ways. See above link to the PHP date function page to see all the different ways of formatting. Then I have another variable that was assigned another date value from the database:

$car_end_date = $custom["car_end_date"][0];

Then I do an if statement and using PHP srttotime function, I can compare the dates. The PHP srttotime function “Parses about any English textual datetime description into a Unix timestamp”. So running both date variables though these function now we have both dates formatted exactly the same. We can now compare Apples to Apples instead of comparing my formatted date to whatever format date I got back from the database. That is it. Here is my code segment to see how it works. I hope this post has helped someone and saved them some time Goggling and searching the internet.

$car_end_date = $custom["car_end_date"][0];
$todaysDate = date("m/d/y");
if (strtotime($car_end_date) > strtotime($todaysDate))
{
     echo 'Yes';
}
else
{
     echo 'No';
}

Adding Dashicons to Custom Post Types Admin Menu

OK, WordPress Designers and Developers. I finally have figured out how to use the new Dashicons. If you do not know what the Dashicons are, go to the website here. With WordPress getting a nice overhaul in the admin theme, Dashicons are used throughout the new admin theme. So I just got finished making a new plugin which required a custom post type. So I wanted to give the new post type a cool new Dashicon then the default pin. So here are the steps:

1. In the custom post type script where you normally state the menu_icon this is what your syntax will be (see highlighted line # 22):

function create_orl_books()
{
register_post_type( 'orl_books',
  array(
    'labels' => array(
    'name' => 'ORL books',
    'singular_name' => 'ORL Book',
    'add_new' => 'Add New',
    'add_new_item' => 'Add New ORL Book',
    'edit' => 'Edit',
    'edit_item' => 'Edit ORL Book',
    'new_item' => 'New ORL Book',
    'view' => 'View',
    'view_item' => 'View ORL Book',
    'search_items' => 'Search ORL Book',
    'not_found' => 'No ORL Book found',
    'not_found_in_trash' =>
    'No ORL Book found in Trash'
    ),
    'public' => true,
    'menu_position' => 15,
    'menu_icon' => 'dashicons-[book]',    'supports' => array('title', 'editor', 'thumbnail')
    )
  );
}

2. OK. Now we know where to place the code correctly, how do we get the Dashicons? Go to the Dashicons website and find the icon that you would like to use.Click on the icon and go back to the top of the Dashicon home page and click on copy html. There you will see what the CSS class is and get that name and place it in the brackets on the menu-icon line.

3. Save your css page and then refresh your admin webpage and this is what you should see:

ASP.NET 4.0 Website Fix for IE 11

OK. This article ASP.NET 4.0 Website Fix for IE 11 will show you how to fix your websites that break in IE 11.  This is for anyone that has discovered the new IE 11 User Agent String issue. This is for all web sites, applications. projects that are targeted at the ASP.NET 4.0 framework. The main issue is the new IE 11 User Agent and the bug in the 4.0 framework. I will describe what the issues is and then show the fix. It is easier than upgrading your web server and all of your ASP.NET applications up to the 4.5 framework. The 4.5 framework has the user agent string bug fixed. So here is the details:

First there is a bug in the ASP.NET 4.0 framework when it reads the User Agent Strings. Here is the article talking about this issue from Scott Hanselman:

http://www.hanselman.com/blog/IE10AndIE11AndWindows81AndDoPostBack.aspx.

The bug causes the Post Back functions to not work. So when trying to view our ASP.NET 4.0 website in IE 11 our site would not work. All of our Post Back functionality was gone. So I tried using the Microsoft magic line of code to fix this issue by forcing IE to emulate IE10.

Microsoft Magic Line of Code: <meta http-equiv=”X-UA-Compatible” content=”IE=EmulateIE10″/>

Well this did not work. It forced IE11 to display site in IE10 mode but it kept the User Agent String as Default which would break the site. I then opened up IE 11 Developer Tools and then switched the User Agent String to IE 10 and BOOM, Goes the Dynamite! It worked. The site Post Back functionality is working. So I knew something was wrong. It would force IE to go to whatever IE version I chose, but it kept the User Agent String at Default, thus breaking the website. Image 1 shows dev tools and the website in IE 10 with User Agent String as default breaking the website.

ieIssue

 

image 2 show dev tools and the website in IE 10 and me manually changing the User String Agent to IE 10 and the website works.

 

ieIssueFx

 

So after many hours of research, I found out that Microsoft changed the IE 11 User Agent String. This caused IE 11 to stay at Default for User Agent String because it has been confused by the change. It is what I found out about the new IE 11 User Agent String: This is from the Microsoft website:

Here is the user agent string from IE 11 on a Windows 8.1 machine: Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko

IE 11 on Windows 7 machine: Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko

Older IE 10 Use Agent String Version: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)

IE 9 User Agent String Version:

See in the past, to identify Internet Explorer just search for the string “MSIE” in the user-agent string. If present, the browser is Internet Explorer. Now that is gone in IE 11. Also they added ‘Mozilla’ and ‘like Gecko’ in IE 11 User Agent String. This sounds like a Firefox browser.

Here is the link from Microsoft about the IE 11 changes:

http://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx

OK. Anyway enough about the issue. How the heck do we fix this. One fix that I read was to upgrade from the ASP.NET 4.0 framework to the 4.5 framework. I figured out an easier way around this. OK, we need to create an ASP.NET folder named, App_Browsers. This ASP.NET folder is the one most unknown. Here is a link to read more about the App_Browsers folder:

http://www.shubho.net/2011/01/what-is-appbrowsers-folder-in-aspnet.html

Now we just add a file with the extension .browser in this folder. Place this code in the file and save. Restart your IIS server and it works.

<browsers>
  <browser id="IE11" parentID="Mozilla">
    <identification>
      <useragent match="Trident\/7.0; rv:(?'version'(?'major'\d+)(\.(?'minor'\d+)?)(?'letters'\w*))(?'extra'[^)]*)"></useragent>
      <useragent nonMatch="IEMobile"></useragent>
    </identification>
    <capture>
      <useragent match="Trident/(?'layoutVersion'\d+)"></useragent>
    </capture>
    <capabilities>
      <capability name="browser"              value="IE"></capability>
      <capability name="layoutEngine"         value="Trident"></capability>
      <capability name="layoutEngineVersion"  value="${layoutVersion}"></capability>
      <capability name="extra"                value="${extra}"></capability>
      <capability name="isColor"              value="true"></capability>
      <capability name="letters"              value="${letters}"></capability>
      <capability name="majorversion"         value="${major}"></capability>
      <capability name="minorversion"         value="${minor}"></capability>
      <capability name="screenBitDepth"       value="8"></capability>
      <capability name="type"                 value="IE${major}"></capability>
      <capability name="version"              value="${version}"></capability>
    </capabilities>
  </browser>
 
  <!-- Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11,0) like Gecko -->
  <browser id="IE110" parentID="IE11">
    <identification>
      <capability name="majorversion" match="11"></capability>
    </identification>
 
    <capabilities>
      <capability name="ecmascriptversion"    value="3.0"></capability>
      <capability name="jscriptversion"       value="5.6"></capability>
      <capability name="javascript"           value="true"></capability>
      <capability name="javascriptversion"    value="1.5"></capability>
      <capability name="msdomversion"         value="${majorversion}.${minorversion}"></capability>
      <capability name="w3cdomversion"        value="1.0"></capability>
      <capability name="ExchangeOmaSupported" value="true"></capability>
      <capability name="activexcontrols"      value="true"></capability>
      <capability name="backgroundsounds"     value="true"></capability>
      <capability name="cookies"              value="true"></capability>
      <capability name="frames"               value="true"></capability>
      <capability name="javaapplets"          value="true"></capability>
      <capability name="supportsCallback"     value="true"></capability>
      <capability name="supportsFileUpload"   value="true"></capability>
      <capability name="supportsMultilineTextBoxDisplay" value="true"></capability>
      <capability name="supportsMaintainScrollPositionOnPostback" value="true"></capability>
      <capability name="supportsVCard"        value="true"></capability>
      <capability name="supportsXmlHttp"      value="true"></capability>
      <capability name="tables"               value="true"></capability>
      <capability name="supportsAccessKeyAttribute"    value="true"></capability>
      <capability name="tagwriter"            value="System.Web.UI.HtmlTextWriter"></capability>
      <capability name="vbscript"             value="true"></capability>
    </capabilities>
  </browser>
</browsers>

 

Here is the link where I found this nice piece of code: http://stackoverflow.com/questions/18244223/webform-dopostbackwithoptions-is-undefined-in-ie11-preview/19585664#19585664