Ajax Tutorials, Tricks, and Code Examples Tue, 01 Apr 2014 19:28:10 +0000 en-US hourly 1 http://wordpress.org/?v=3.9.1 Using PHP AJAX /php/using-php-ajax/ /php/using-php-ajax/#comments Tue, 01 Apr 2014 19:28:10 +0000 /?p=490 Introduction In this AJAX tutorial we will learn how to make a PHP AJAX call to display data to the user. We will create form that where users will input […]

The post Using PHP AJAX appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
Introduction

In this AJAX tutorial we will learn how to make a PHP AJAX call to display data to the user. We will create form that where users will input their name and while they are typing, a list of suggested names will appear and be able to be selected. We are essentially trying to replicate a situation where the user may require the computer’s input to make a recommendation.

The HTML Markup and Javascript

In order to make the AJAX call work, we must tell the computer when to execute this action. What better way to do this then by Javascript. With Javascript, we can tell the computer that “when the user releases a keyboard key while typing in the input field, execute the Javascript and make the AJAX call”. Let’s set up our HTML.

<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","namehints.php?n="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form> 
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>

There are a few lines of conditional statements that will guide the browser in making the appropriate decision in executing the AJAX call.

  • First, clear the textHint ID area
  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready (.onreadystatechange line)
  • Send the request off to a file on the server
  • Notice that a parameter (n) is added to the URL (with the content of the input field which is +str)

PHP

As you may have noticed from the previous step, there is an http request to a file called namehints.php. The AJAX call has been created when the user releases the keyboard key and we must now create and place a document named “namehint.php” in the proper folder for the AJAX to refer to. Create the document and place the following code inside the document.

Our namehint.php file

<?php
// Fill up array with names
$a[]="Annie";
$a[]="Bethany";
$a[]="Cindy";
$a[]="Dane";
$a[]="Ella";
$a[]="Fred";
$a[]="Greg";
$a[]="Hugh";
$a[]="Ingrid";
$a[]="John";
$a[]="Kate";
$a[]="Lola";
$a[]="Noel";
$a[]="Oscar";
$a[]="Peter";
$a[]="Aaron";
$a[]="Ron";
$a[]="Clyde";
$a[]="Don";
$a[]="Ellen";
$a[]="Sunny";
$a[]="Tyler";
$a[]="Vivian";
$a[]="Lisa";
$a[]="Ellie";
$a[]="Wayne";
$a[]="Wenchao";
$a[]="Victor";

// get the n parameter from URL
$n=$_REQUEST["n"]; $hint="";

// lookup all hints from array if $n is different from "" 
if ($n !== "")
  { $n=strtolower($n); $len=strlen($n);
    foreach($a as $name)
    { if (stristr($n, substr($name,0,$len)))
      { if ($hint==="")
        { $hint=$name; }
        else
        { $hint .= ", $name"; }
      }
    }
  }

// Output "no suggestion" if no hint were found
// or output the correct values 
echo $hint==="" ? "no suggestion" : $hint;
?>

There is definitely a lot of information here so lets go over what we are inputting.

  • The first section is a long array list which we’ve named $a with all the names that can be suggested. The longer the list, the more comprehensive of a recommendation you can make.
  • Next we get the ‘n’ parameter that is requested in the URL along with the $hint variable which we will give it a no value.
  • Create the function to be executed when the server response is ready (.onreadystatechange line)
  • Now starts our conditional, if $n is something other than blank, continue the with the PHP code
  • Inside this condition, that has variables: one to convert $n into lowercase strings and to get the string length of $n. After that we run a foreach loop changing our array $a into $name.
  • Inside this loop we determine to place a name depending on how long the string is and if it matches any of them as well as placing one hint or two hints.
  • Our line is a conditional that states ” if $hint has no value, output ‘no suggestion’, if not output $hint (a value that is stored from the foreach loop)”

Let’s break it down into a much simpler explanation: Create a Javascript that makes an AJAX call when the user types in the textarea. The AJAX will will request and run a PHP code from our PHP file. In this file we created a list of recommended names. Our PHP code will loop through these names and output the names based off of what strings were submitted.

Wrapping It Up

PHP is a very flexible language and can help you communicate with the server and execute many different kinds of functions. Besides making an AJAX call to a file, you can also call to a database or XML file to request valuable data and display it to your users as well. Take your PHP skills further and try practicing with these new ideas.

The post Using PHP AJAX appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/php/using-php-ajax/feed/ 0
More Tips for using JQuery AJAX /jquery/more-tips-for-using-jquery-ajax/ /jquery/more-tips-for-using-jquery-ajax/#comments Mon, 24 Mar 2014 17:43:28 +0000 /?p=486 Introduction In one of our previous tutorials Getting Starting with AJAX using JQuery, we went over the basics of using Ajax. What if you wanted more control? Say you wanted […]

The post More Tips for using JQuery AJAX appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
Introduction

In one of our previous tutorials Getting Starting with AJAX using JQuery, we went over the basics of using Ajax. What if you wanted more control? Say you wanted to run a function when the AJAX experiences an error? We will go over some more approaches to handling AJAX using JQuery.

The $.ajaxSetup() Method

This Ajax method is a very helpful method. The .ajaxSetup method is used to set default values for future AJAX requests. The proper syntax and usage goes as follows:

$.ajaxSetup({name:value, name:value, ... })

This can be very helpful to customize your Ajax request and “debug” certain instances of your project. There are two parameters you can pass, the name (anyone one of the 24 like cache, password etc.) and the value of that category name. Here is an example. Did you know that IE always Caches Ajax requests? So many times when viewing the AJAX on your site, it may be a cached state from your last session? To override this, we would use .ajaxSetup and specify a name and value. Here is our example to get rid of AJAX caching.

$.ajaxSetup ({
    cache: false
});

The $.getJSON() method

$(selector).getJSON(url,data,success(data,status,xhr))

Both the data and success are optional values. As you can see the JSON call is very similar to your standard AJAX call, except for the Success parameter which is will display a status string (“success”, “notmodified”, “error”, “timeout”, or “parsererror”) upon a successful JSON request.

$("button").click(function(){
  $.getJSON("demo_ajax_json.js",function(result){
    $.each(result, function(i, field){
      $("div").append(field + " ");
    });
  });
});

This one is a little more complex but is quite simple. You make the request using .getJSON and mention the http url (demo_ajax_json.js). The function contains some coding the will display the result field of the JSON script and append it after the div field.

The $.ajaxComplete() method

This ajax method is pretty self explanatory but is very useful. This method will run a function once the ajax has been completed, whether or not the ajax call was successful or not.

$(document).ajaxComplete(function(event,xhr,options))

The $.ajaxSend() method

Use the ajaxSend() method to help pass a function to run when an AJAX requests is about to be sent. This can be very helpful to display a graphic or helpful string of text to notify the user of the ajax progress or update.

$(document).ajaxSend(function(event,xhr,options))

The $.ajaxSuccess() method

The ajaxSuccess() method specifies a function to be run when an AJAX request is successfully completed. Using this Ajax method can be helpful to verify or ensure that the AJAX call was sent successfully.

$(document).ajaxSuccess(function(event,xhr,options))

The $.ajaxError() method

The ajaxError() method specifies a function to be run when an AJAX request fails. This method is your go to method to let the user know that their ajax request has failed and is commonly followed by an alert.

$(document).ajaxError(function(event,xhr,options,exc))

AJAX is a great way to to help optimize your site by reducing loading all of your content at once. Think of it as a way to store and pull your files for later use instead of throwing it at the user all at once. For more details and useful AJAX methods, visit W3 Schools JQuery AJAX Methods.

The post More Tips for using JQuery AJAX appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/jquery/more-tips-for-using-jquery-ajax/feed/ 0
Create a Self-Validating AJAX Email Input with AngularJS /quickstart/create-self-validating-ajax-email-input-angularjs/ /quickstart/create-self-validating-ajax-email-input-angularjs/#comments Fri, 03 Jan 2014 20:43:51 +0000 /?p=430 Introduction In this tutorial we’re going to be using the AngularJS library to create a self validating email input in html. We’re using AngularJS to extend the capabilities of our […]

The post Create a Self-Validating AJAX Email Input with AngularJS appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
Introduction

In this tutorial we’re going to be using the AngularJS library to create a self validating email input in html. We’re using AngularJS to extend the capabilities of our HTML, but don’t want to get involved with the pesky DOM.

Prepping Our View

Before we get into AngularJS, we need to create our html view. Write something similar to the following to get started:

<!doctype html>
<html>
  <head>
 <title>Our AngularJS Input</h3>
  </head>
  <body>
    <form name="myForm">
      Email: <input type="email" name="input" required>
    </form>
  </body>
</html>

As you can see the only element that is visible in the browser is our email input. Now that we have our view, we can dive into the AngularJS functionality, and validate our input.

Prepping The View

First we need to specify that this is an AngularJS application. To do so, we need to add “ng-app” to the opening html tag, add a controller to the form, and then reference our script in the head tag.

<!doctype html>
<html ng-app>
  <head>
 <title>Our AngularJS Input</h3>
 <script src="http://code.angularjs.org/1.2.6/angular.min.js"></script>
  </head>
  <body>
    <form name="myForm" ng-controller="Ctrl">
      Email: <input type="email" name="input" required>
    </form>
  </body>
</html>

Adding The Validation

Now we can start validating our e-mail input. First, let’s add a model to our input markup:

Email: <input type="email" name="input" ng-model="textInput" required>

We’re going to have to define the scope of our input, so let’s create a script tag and write a function that helps us do that.

<!doctype html>
<html ng-app>
  <head>
 <title>Our AngularJS Input</h3>
  <script src="http://code.angularjs.org/1.2.6/angular.min.js"></script>
  <script>
    function Ctrl($scope) {
      $scope.textInput = 'me@example.com';
    }
   </script>
  </head>
  <body>
    <form name="myForm" ng-controller="Ctrl">
      Email: <input type="email" name="input" ng-model="textInput" required>
    </form>
  </body>
</html>

Now that we have the scope defined we can create our validations and produce error messages for invalid data:

<!doctype html>
<html ng-app>
  <head>
 <title>Our AngularJS Input</h3>
  <script src="http://code.angularjs.org/1.2.6/angular.min.js"></script>
  <script>
    function Ctrl($scope) {
      $scope.textInput = 'me@example.com';
    }
   </script>
  </head>
  <body>
    <form name="myForm" ng-controller="Ctrl">
      Email: <input type="email" name="input" ng-model="textInput" required>
      <span class="error" ng-show="myForm.input.$error.required">This data field is required.</span>
      <span class="error" ng-show="myForm.input.$error.email">Please enter a valid email address.</span>
    </form>
  </body>
</html>

When we test our code in the browser, we can see that the input form is now validating asynchronously on the fly. For more help and resources on AngularJS visit angularjs.org

The post Create a Self-Validating AJAX Email Input with AngularJS appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/quickstart/create-self-validating-ajax-email-input-angularjs/feed/ 0
Getting started with AJAX using JQuery /jquery/getting-started-ajax-using-jquery/ /jquery/getting-started-ajax-using-jquery/#comments Mon, 14 Oct 2013 14:22:27 +0000 /?p=414 Introduction JQuery AJAX methods allow developers to load data from external sources and place it into the html of a web page, all without having to reload the page. This […]

The post Getting started with AJAX using JQuery appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
Introduction

JQuery AJAX methods allow developers to load data from external sources and place it into the html of a web page, all without having to reload the page. This tutorial will show you the basic JQuery AJAX methods and how to use them in context.

The load() method

The basic syntax of the JQuery load() method:

$(selector).load(URL,data,callback);

The URL parameter specifies the URL that your method is loading. The data parameter is optional, and can specify key/value pairs to send with the request. The callback parameter is also optional. This parameter may define the name of the function to execute after the load() method is executed.

The .get() method

The GET method is requests data from a specified resource. GET is used for getting some data from the server. The GET method can return cached data.

In JQuery we use .get() for a GET HTTP request.

$.get(URL,callback);

The URL parameter specifies the URL that you are requesting. The callback parameter, which is optional, can hold the name of a function that you want to execute if the request succeeds.

$("button").click(function(){
  $.get("demo_test.asp",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

In the above example, the .get() method is executed when the button is clicked. The URL we are requesting in this example is “demo_test.asp”. The second parameter is the callback function. In this example, the callback specifies the status of this request.

The .post() method

The POST HTTP request can retrieve data from the server. This request method does not cache data, and usually sends data along with the request.

In JQuery we use .post() for a POST HTTP request.

$.post(URL,data,callback);

The URL parameter specifies the URL that your method is loading. The data parameter is optional, and can specify key/value pairs to send with the request. The callback parameter is also optional. This parameter may define the name of the function to execute after the load() method is executed.

$("button").click(function(){
  $.post("demo_test_post.asp",
  {
    name:"Donald Duck",
    city:"Duckburg"
  },
  function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

In the above example, the .post() method is executed when the button is clicked. The URL in this particular example is “demo_test_post.asp”. We are passing the name and city key/value pairs into the request using the optional data parameter. The first callback parameter in our example holds the content of our page that was requested. The second callback parameter is holding the status value of the request.

These three methods are the most popular JQuery AJAX methods. There are many more methods that JQuery has to offer, to see those, check out the W3C JQuery AJAX Reference.

The post Getting started with AJAX using JQuery appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/jquery/getting-started-ajax-using-jquery/feed/ 0
Tutorial: Using AJAX with Dynamic Controls in ASP.NET and C# /general/tutorial-using-ajax-with-dynamic-controls-in-asp-net-and-c/ /general/tutorial-using-ajax-with-dynamic-controls-in-asp-net-and-c/#comments Thu, 26 Sep 2013 18:59:27 +0000 /?p=397 In this tutorial, we will learn how to dynamically create and change controls using AJAX. The tutorial itself is very simple, but the principle can be applied to any control, […]

The post Tutorial: Using AJAX with Dynamic Controls in ASP.NET and C# appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
In this tutorial, we will learn how to dynamically create and change controls using AJAX. The tutorial itself is very simple, but the principle can be applied to any control, giving powerful results.

We will simply create 3 custom controls and use a dropdown list to change these controls.

We create three WebControls: BlueControl.ascx, GreenControl.ascx and RedControl.ascx all with similar code as below:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="BlueControl.ascx.cs" Inherits="BlueControl" %>

<div style="background-color: Blue; width: 200px; height: 200px">
</div>

On Default.aspx, we add a ScriptManager, UpdatePanel, DropDownList and a PlaceHolder:

<form id="frmMain" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<h2>Using AJAX to Dynamically Create Controls</h2>
<div>
<table width="500">
<tr valign="top">
<td style="width: 150px">
<span style="font-size: 10pt">Choose Color:<br />
</span>
<asp:DropDownList ID="ddColor" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddColor_SelectedIndexChanged" Width="100px">
<asp:ListItem Selected="True">Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:DropDownList></td>
<td>
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>

<asp:PlaceHolder ID="placeHolder" runat="server"></asp:PlaceHolder>

</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddColor" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
</div>
</form>

The code-behind will look something like this:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SetColor();
}

protected void ddColor_SelectedIndexChanged(object sender, EventArgs e)
{
SetColor();
}

private void SetColor()
{
Control c = Page.LoadControl(ddColor.SelectedValue +
"Control.ascx");

placeHolder.Controls.Clear();
placeHolder.Controls.Add(c);
}
}

Web.config will look something like this:

<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<system.web>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
<system.web.extensions>
<scripting>
<webServices>
<!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
<!--
<jsonSerialization maxJsonLength="500">
<converters>
<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
</converters>
</jsonSerialization>
-->
<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
<!--
<authenticationService enabled="true" requireSSL = "true|false"/>
-->
<!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
writeAccessProperties attributes. -->
<!--
<profileService enabled="true"
readAccessProperties="propertyname1,propertyname2"
writeAccessProperties="propertyname1,propertyname2" />
-->
</webServices>
<!--
<scriptResourceHandler enableCompression="true" enableCaching="true" />
--> </scripting>
</system.web.extensions>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</system.webServer>
</configuration>

Download Source Files

The post Tutorial: Using AJAX with Dynamic Controls in ASP.NET and C# appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/general/tutorial-using-ajax-with-dynamic-controls-in-asp-net-and-c/feed/ 0
Using the JavaScript String Object in Visual Studio ASP.NET 4.0 /javascript/using-the-javascript-string-object-in-visual-studio-asp-net-4-0/ /javascript/using-the-javascript-string-object-in-visual-studio-asp-net-4-0/#comments Wed, 25 Sep 2013 19:54:58 +0000 /?p=394 Welcome to another AJAX tutorial, This is our introductory mini series into JavaScript. Today we will be learning about the JavaScript String Objects. JavaScript is an Object Oriented Programming (OOP) […]

The post Using the JavaScript String Object in Visual Studio ASP.NET 4.0 appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
Welcome to another AJAX tutorial, This is our introductory mini series into JavaScript. Today we will be learning about the JavaScript String Objects.

JavaScript is an Object Oriented Programming (OOP) language. A JavaScript object has properties and methods. Properties are values that are tagged to the object. A Method of an object refers to the actions than can be performed by the object.

Example: The String JavaScript object has a length property and toUpperCase() method. The Length property of the string object returns the length of the string, that is in other words the number of characters present in the string. toUpperCase() method converts all the letters of the string to upper case. Similarly the toLowerCase() method converts all the letters of the string to lower case.

<script type="text/javascript">
    var txt = "Hello World!"
    document.write(txt.length);
    document.write("<br />");
    document.write(txt.toUpperCase());
</script>

If you run this the output should be:

There are built-in objects available in JavaScript. It is also possible for a JavaScript programmer to define his own objects and variable types. In this tutorial, you will learn how to make use of some of the built-in objects available in JavaScript.

Built-in Objects
Some of the built-in objects available in JavaScript are:

• String
• Date
• Math
• Array
• Object

Of the above objects, the most widely used one is the String object. Objects are nothing but special types of data. Each object has Properties and Methods associated with it.

The JavaScript String Object
The String object is used to manipulate a stored piece of text. String objects are created with a new String() method.

Syntax: var txt = new String(string); or var txt = string;

String Object Properties

Property

Description

constructor

Returns the function that created the String object’s prototype

length

Returns the length of a string

prototype

Allows you to add properties and methods to an object

The main use of string object is to store text. The methods used in String Objects are:

• charAt()
• charCodeAt()
• concat()
• indexOf
• lastIndexOf
• substring()
• toUpperCase()
• toLowerCase()
• charAt()
• match()
• split()
• replace()

1) charAt()

The charAt() method returns the character at the specified index in a string.The index of the first character is 0, and the index of the last character in a string called “txt”, is txt.length-1.

Syntax: string.charAt(index)

Index: Required. An integer between 0 and string.length-1

Example

<script type="text/javascript">
    var str = "Hello world!";
    document.write("First character: " + str.charAt(0) + "<br />");
    document.write("Last character: " + str.charAt(str.length - 1));
</script>

And when you run that the results will be

2) charCodeAt()

The charCodeAt() method returns the Unicode of the character at the specified index of a string.The index of the first character is 0, and the index of the last character in a string called “txt”, is txt.length-1.

Syntax: string.charCodeAt(index)

index:Required. An integer between 0 and string.length-1

Example

<script type="text/javascript">
    var str = "Hello world!";
    document.write("First character: " + str.charCodeAt(0) + "<br />");
    document.write("Last character: " + str.charCodeAt(str.length - 1));
</script>

And here is what our output would be:

3) concat()

The concat() method is used to join two or more strings.This method does not change the existing strings, it only returns a copy of the joined strings.

Syntax: string.concat(string2, string3, …, stringX) string2, string3, …, stringX: Required.

The strings to be joined

Example 1

<script type="text/javascript">
    var str1 = "Hello ";
    var str2 = "world!";
    document.write(str1.concat(str2));
</script>

Here is our output

Here is our 2nd example

<script type="text/javascript">
    var str1 = "Hello ";
    var str2 = "world!";
    var str3 = " Have a nice day!";
    document.write(str1.concat(str2, str3));
</script>

4) indexOf
If we want to know the position of a character or group of characters in a String Object we use the indexOf method.

Syntax is indexOf(substr, [start])

‘substr’ is a character or group of characters whose position we want to determine. ‘start’ is an optional argument. It tells the position from where to begin the search. The order of the search is from beginning to the end of the string. If there are multiple occurrences of ‘substr’ it will return the position of the first occurrence. If no match is found, then it will return -1;

Example

<script type="text/javascript">
    var exf = "This is cool";
    document.write(exf.indexOf("This ") + "<br />")
    document.write("<br />");
    document.write(exf.indexOf("Cool ") + "<br />")
</script>

Here is our output from our indexOf(substr, [start])

Since we searched the position of ‘Cool’ which is different from ‘cool’,it returned -1. We have already learned that javascript is case sensitive.

5) lastIndexOf

Syntax is lastIndexOf(substr, [start])

Everything is similar to the indexOf method except that the order of search is from the end to beginning of the string.

Example :- “character”.lastIndexOf(“c”) will give the output 5

Substr

Syntax is substr(start, [length])

Substr returns the characters in a string beginning at the “start” and through the specified number of characters, “length”. “Length” is optional, and if omitted, up to the end of the string is assumed.

<script type="text/javascript">
         var exf="excellent";
         document.write(exf.substring(0,4) + "<br />")
         document.write("<br />");
         document.write(exf.substring(2,4)) + "<br />")
</script>

6) charAt()

syntax is charAt(position)

charAt returns the character at the specified position.

Example

<script type="text/javascript">
    var txt = "welcome";
    document.write(txt.charAt(1) + "<br />")
    document.write("<br />");
    document.write(txt.charAt(0) + "<br />")
</script>

Here is the output

7)match()

syntax is string.match(regexp)
The match() method searches for a match between a regular expression and a string, and returns the matches.This method returns an array of matches, or null if no match is found.

Example:

<script type="text/javascript">
    var str = "The rain in SPAIN stays mainly in the plain";
    var exp = /ain/gi;
    document.write(str.match(exp));
</script>

This performs a global case insensitive search for “ain”.

The output of the code above will be: ain,AIN,ain,ain

8) split()
The split() method is used to split a string into an array of substrings, and returns the new array.

The syntax is string.split(separator, limit) Both parameters are optional. The separator is the character to use for splitting. The Limit is the integer parameter which specifies the number of splits.

Example

<script type="text/javascript">
    var str = "Are you free today?";
    document.write(str.split() + "<br />");
    document.write(str.split(" ") + "<br />");
    document.write(str.split("") + "<br />");
    document.write(str.split(" ", 3));
</script>

9)replace()
The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring.

The syntax is string.replace(regexp/substr,newstring)

Both parameters are required. regexp/substr is a substring or a regular expression. Newstring is the string to replace the found value in parameter 1.

Examples

Perform a case-sensitive search:

<script type="text/javascript">
    var str = "Visit Microsoft!";
    document.write(str.replace("Microsoft", "W3Schools"));
</script>

Perform a case-insensitive search:

<script type="text/javascript">
    var str = "Visit Microsoft!";
    document.write(str.replace(/microsoft/i, "W3Schools"));
</script>

Perform a global, case-insensitive search (the word Microsoft will be replaced each time it is found):

<script type="text/javascript">
    var str = "Welcome to Microsoft! ";
    str = str + "We are proud to announce that Microsoft has ";
    str = str + "one of the largest Web Developers sites in the world.";
    document.write(str.replace(/microsoft/gi, "W3Schools"));
</script>

10)Search()

The search() method searches for a match between a regular expression and a string. This method returns the position of the match, or -1 if no match is found.

Syntax: string.search(regexp)

Examples
Perform a case-sensitive search:

<script type="text/javascript">
    var str = "Visit W3Schools!";
    document.write(str.search("W3SCHOOLS"));
</script>

Perform a case-insensitive search:

OUTPUT

11) Slice()

The slice() method extracts a part of a string and returns the extracted part in a new string. Otherwise it returns -1.
Syntax: string.slice(begin,end)

begin: Required. The index where to begin the extraction. First character is at index 0 end: Optional. Where to end the extraction. If omitted, slice() selects all characters from the begin position to the end of the string

Example

<script type="text/javascript">
    var str = "Hello happy world!";
    // extract all characters, start at position 0:
    document.write(str.slice(0) + "<br />");
    // extract all characters, start at position 6:
    document.write(str.slice(6) + "<br />");
    // extract from the end of the string, and to position -6:
    document.write(str.slice(-6) + "<br />");
 
    // extract only the first character:
    document.write(str.slice(0, 1) + "<br />");
    // extract the characters from position 6 to position 11:
    document.write(str.slice(6, 11) + "<br />");
</script>

OUTPUT

12) Split()

The split() method is used to split a string into an array of substrings, and returns the new array. If an empty string (“”) is used as the separator, the string is split between each character.

Syntax: string.split(separator, limit)

separator: Optional. Specifies the character to use for splitting the string. If omitted, the entire string will be returned.
limit: Optional. An integer that specifies the number of splits.

Example

<script type="text/javascript">
    var str = "How are you doing today?";
    document.write(str.split() + "<br />");
    document.write(str.split(" ") + "<br />");
    document.write(str.split("") + "<br />");
    document.write(str.split(" ", 3));
</script>

OUTPUT

13) substr()

The substr() method extracts the characters from a string, beginning at “start” and through the specified number of character, and returns the new sub string.

Syntax: string.substr(start,length)

Start: Required. The index where to start the extraction. First character is at index 0. length: Optional. The number of characters to extract. If omitted, it extracts the rest of the string

Example

<script type="text/javascript">
    var str = "Hello world!";
    document.write(str.substr(3) + "<br />");
    document.write(str.substr(3, 4));
</script>

OUTPUT

14) substring()

The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string. This method extracts the characters in a string between “from” and “to”, not including “to” itself.

Syntax: string.substring(from, to)

from: Required. The index where to start the extraction. First character is at index 0. to: Optional. The index where to stop the extraction. If omitted, it extracts the rest of the string.

Example

<script type="text/javascript">
    var str = "Hello world!";
    document.write(str.substring(3) + "<br />");
    document.write(str.substring(3, 7));
</script>

OUTPUT

15)toLowerCase() and toUpperCase()

The toLowerCase() method converts a string to lowercase letters. The toUpperCase() method converts a string to uppercase letters.

Syntax: string.toLowerCase() and string.toUpperCase()

Example

<script type="text/javascript">
    var txt = "Hello World!";
    document.write(txt.toLowerCase() + "<br />");
    document.write(txt.toUpperCase());
</script>

OUTPUT

16) valueOf()

The valueOf() method returns the primitive value of a String object. This method is usually called automatically by JavaScript behind the scenes, and not explicitly in code.

Syntax: string.valueOf()

Example

<script type="text/javascript">
    var str = "Hello world!";
    document.write(str.valueOf());
</script>

OUTPUT

String HTML Wrapper Methods
The HTML wrapper methods return the string wrapped inside the appropriate HTML tag.

Method

Description

anchor()

Creates an anchor

big()

Displays a string using a big font

blink()

Displays a blinking string

bold()

Displays a string in bold

fixed()

Displays a string using a fixed-pitch font

fontcolor()

Displays a string using a specified color

fontsize()

Displays a string using a specified size

italics()

Displays a string in italic

link()

Displays a string as a hyperlink

small()

Displays a string using a small font

strike()

Displays a string with a strikethrough

sub()

Displays a string as subscript text

sup()

Displays a string as superscript text

And that about completes our tutorial on the basics of JavaScript Objects.

We are looking forward to you learning AJAX and JavaScript so you may fully utilize these tools to better your WEB 2.0 website.

The post Using the JavaScript String Object in Visual Studio ASP.NET 4.0 appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/javascript/using-the-javascript-string-object-in-visual-studio-asp-net-4-0/feed/ 0
Tutorial: Dynamic DropDownList with AJAX in ASP.NET and C# /general/tutorial-dynamic-dropdownlist-with-ajax-in-asp-net-and-c/ /general/tutorial-dynamic-dropdownlist-with-ajax-in-asp-net-and-c/#comments Wed, 25 Sep 2013 19:11:10 +0000 /?p=389 This tutorial will show how we can make DropDownLists more dynamic by using AJAX in ASP.NET 2.0 and C#. First, we will need to import the namespace from System.Data.SqlClient. The […]

The post Tutorial: Dynamic DropDownList with AJAX in ASP.NET and C# appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
This tutorial will show how we can make DropDownLists more dynamic by using AJAX in ASP.NET 2.0 and C#.
First, we will need to import the namespace from System.Data.SqlClient.

using System.Data.SqlClient;

The System.Data.SqlClient namespace contains The System.Data.SqlClient namespace is the .NET Framework Data Provider for SQL Server. The .NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space.
In order to working with AJAX, we need XMLHttpRequest object. With the XMLHttpRequest object, Microsoft Internet Explorer clients can retrieve and submit XML data directly to a Web server without reloading the page. To convert XML data into renderable HTML content, use the client-side XML DOM or Extensible Stylesheet Language Transformations (XSLT) to compose HTML elements for presentation. In tutorial, we need a DropDownLists with being embed also.

The code is simple, there is nothing complex in it. In the page load event, I am register the attribute of Drowdownlist. It is for checking whether the ProvinceID is empty. If it is not be empty, I will call the function bind.

if (!Page.IsPostBack)
{
this.DropDownList1.Attributes.Add("onchange", "return startRequest();");
ListProvince();
if (ProvinceID != "")
{
GetCityByProvinceID(ProvinceID);
}
}

private DataSet GetDataSet(string sql)
{
string constring=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
SqlDataAdapter sda =new SqlDataAdapter(sql,constring);
DataSet ds=new DataSet();
sda.Fill(ds);
return ds;
}

private void GetCityByProvinceID(string ProvinceID)
{
string connStr = ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(connStr);
string sql = "select * from authors where au_id='" + ProvinceID + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();

string s = @"<table cellspacing='0' cellpadding='4' border='0' id='GridView1' style='color:#333333;border-collapse:collapse;'>";
s+="<tr style='color:White;background-color:#990000;font-weight:bold;'>";
s += "<th scope='col'>Authors_ID</th><th scope='col'>FirstName</th><th scope='col'>City</th>
<th scope='col'>Phone</th><th scope='col'>state</th><th scope='col'>zip</th></tr>";
int m = 0;
while (dr.Read())
{
if (m % 2 == 0)
{
s += "<tr style='color:#333333;background-color:#FFFBD6;'>";
}
else
{
s += "<tr style='color:#333333;background-color:White;'>";
}
m++;
s += "<td>" + dr["au_id"] + "</td>";
s += "<td>" + dr["au_fname"] + "</td>";
s += "<td>" + dr["city"] + "</td>";
s += "<td>" + dr["phone"] + "</td>";
s += "<td>" + dr["state"] + "</td>";
s += "<td>" + dr["zip"] + "</td>";
s += "</tr>";</tr>
}
s+="</table>";
dr.Close();
conn.Close();
this.Response.Write(s);
this.Response.End();
}

Every DropDownList is rendered as a SELECT element in HTML. Each of these elements has its controller, called AjaxDropDownController. The controller has a lot of things to do:

Execute asynchronous request to web server to get data.
Populate the dropdownlist.
Listen to the change event of dropdownlist.
Be the observer and the observable.
Persist the content of dropdownlist in the client side.

When the controller needs to update its dropdownlist, it will call startRequest(). While calling these methods, it may pass a filter string, which is the name-value pair of the dropdownlist that it depends to. Inside the ProvinceID value, a request URL is constructed which contains the id and filter parameters.

<script type="text/javascript">
var xmlHttp;

function createXMLHttpRequest()
{
if (window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}

function startRequest()
{
//debugger;
var ProvinceID=document.getElementById("DropDownList1");
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "?ProvinceID="+ProvinceID.value, true);
xmlHttp.send(null);
}

function handleStateChange()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
document.getElementById("gridiv").innerHTML=xmlHttp.responseText;
}
}
}
</script>

The front end AjaxDropDownListCsharp2005.aspx page looks something like this:

<div align="center">
<asp:Label ID="Label1" runat="server" Text="Please Slect Author's ID:"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" Width="160px">
</asp:DropDownList>
<br />
</div>

The flow for the code behind page is as follows

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{

this.DropDownList1.Attributes.Add("onchange", "return startRequest();");
ListProvince();
if (ProvinceID != "")
{
GetCityByProvinceID(ProvinceID);
}
}
}

private string ProvinceID
{
get
{
if (Request["ProvinceID"] != null && Request["ProvinceID"].ToString() != "")
{
return Request["ProvinceID"];
}
else
{
return "";
}
}
}

private DataSet GetDataSet(string sql)
{
string constring=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
SqlDataAdapter sda =new SqlDataAdapter(sql,constring);
DataSet ds=new DataSet();
sda.Fill(ds);
return ds;
}

private void GetCityByProvinceID(string ProvinceID)
{
string connStr = ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(connStr);
string sql = "select * from authors where au_id='" + ProvinceID + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();

string s = @"<table cellspacing='0' cellpadding='4' border='0' id='GridView1' style='color:#333333;border-collapse:collapse;'>";
s+="<tr style='color:White;background-color:#990000;font-weight:bold;'>";
s += "<th scope='col'>Authors_ID</th><th scope='col'>FirstName</th><th scope='col'>City</th>
<th scope='col'>Phone</th><th scope='col'>state</th><th scope='col'>zip</th></tr>";
int m = 0;
while (dr.Read())
{
if (m % 2 == 0)
{
s += "<tr style='color:#333333;background-color:#FFFBD6;'>";
}
else
{
s += "<tr style='color:#333333;background-color:White;'>";
}
m++;
s += "<td>" + dr["au_id"] + "</td>";
s += "<td>" + dr["au_fname"] + "</td>";
s += "<td>" + dr["city"] + "</td>";
s += "<td>" + dr["phone"] + "</td>";
s += "<td>" + dr["state"] + "</td>";
s += "<td>" + dr["zip"] + "</td>";
s += "</tr>";
}
s+="</table>";
dr.Close();
conn.Close();
this.Response.Write(s);
this.Response.End();
}
private void ListProvince()
{
string sql = "select * from authors";
DataSet ds = GetDataSet(sql);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "au_id";
DropDownList1.DataValueField = "au_id";
DropDownList1.DataBind();
}
}

The post Tutorial: Dynamic DropDownList with AJAX in ASP.NET and C# appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/general/tutorial-dynamic-dropdownlist-with-ajax-in-asp-net-and-c/feed/ 0
Tutorial: AJAX Dynamic Calendar Control in ASP.NET and C# /general/tutorial-ajax-dynamic-calendar-control-in-asp-net-and-c/ /general/tutorial-ajax-dynamic-calendar-control-in-asp-net-and-c/#comments Wed, 25 Sep 2013 19:06:26 +0000 /?p=387 This tutorial was created with Microsoft’s ASP.NET AJAX Extensions for VS.NET 2005, which can be downloaded here. This brief article will show how easy it is to make the calendar […]

The post Tutorial: AJAX Dynamic Calendar Control in ASP.NET and C# appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
This tutorial was created with Microsoft’s ASP.NET AJAX Extensions for VS.NET 2005, which can be downloaded here.

This brief article will show how easy it is to make the calendar control more dynamic and usable, by implementing AJAX to input the selected date into a textbox for submission without using PostBack.

First, we create an ‘AJAX-Enabled Web Site’ in Visual Studio .NET
Which will give us our ScriptManager tag, and also the AJAX assembly references in the Web.config:

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" />
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>

<system.web>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="false">
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation>

<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>

<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>

<system.web.extensions>
<scripting>
<webServices>
<!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
<!--
<jsonSerialization maxJsonLength="500">
<converters>
<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
</converters>
</jsonSerialization>
-->
<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
<!--
<authenticationService enabled="true" requireSSL = "true|false"/>
-->

<!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
writeAccessProperties attributes. -->
<!--
<profileService enabled="true"
readAccessProperties="propertyname1,propertyname2"
writeAccessProperties="propertyname1,propertyname2" />
-->
</webServices>
<!--
<scriptResourceHandler enableCompression="true" enableCaching="true" />
-->
</scripting>
</system.web.extensions>

<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated" />
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>
</system.webServer>
</configuration>

We create a TextBox control and a Calendar control:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Calendar1" EventName="SelectionChanged" />
</Triggers>
<ContentTemplate>
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>

Note that the Calendar has a OnSelectionChanged attribute, and that both the controls are within the UpdatePanel tags. This will ensure that these controls are refreshed when the trigger is activated.

The only code we need is below. This is executed when the selection of the calendar control is changed (when the user clicks on a new date). When this happens, the method PutDateInBox is called and the date is input into the textbox control, from the calendar control.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
PutDateInBox();
}

protected void PutDateInBox()
{
TextBox1.Text = Calendar1.SelectedDate.ToString("MM/dd/yyyy");
}
}

The post Tutorial: AJAX Dynamic Calendar Control in ASP.NET and C# appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/general/tutorial-ajax-dynamic-calendar-control-in-asp-net-and-c/feed/ 0
Learn how to use Multiple Popup Controls in ASP.NET 3.5 AJAX. C# /general/learn-how-to-use-multiple-popup-controls-in-asp-net-3-5-ajax-c/ /general/learn-how-to-use-multiple-popup-controls-in-asp-net-3-5-ajax-c/#comments Wed, 25 Sep 2013 18:33:38 +0000 /?p=380 This tutorial will use Multiple Popup Controls to populate a textbox in ASP.NET 3.5 AJAX Web App. C# In this tutorial we will use two PopupControl extender’s from the AJAX […]

The post Learn how to use Multiple Popup Controls in ASP.NET 3.5 AJAX. C# appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
This tutorial will use Multiple Popup Controls to populate a textbox in ASP.NET 3.5 AJAX Web App. C#

In this tutorial we will use two PopupControl extender’s from the AJAX Control Toolkit which offers an easy way to trigger a popup if any other control gets activated.

Here is a snapshot of the Popup Control extender:

To start, open Visual Studio 2008. File > New > Web Site > ASP.NET Web site and name it MultPopupCntrl or whatever you would like.

From the Design View of the default.aspx page, locate the Microsoft AJAX extensions tab of the toolbox and double-click the ScriptManager. Then from the same tab double-click the UpdatePanel as well.

Now drag two Textboxes over to the page within the UpdatePanel. Name the first textbox txtBegin, and the second txtEnd. As soon as you are done setting the textbox properties, type in “Begin Date” and “End Date” in front of each corresponding textbox.

<div class="style1"> 
Begin Date:   
<asp:TextBox ID="txtBegin" runat="server">
</asp:TextBox> 
End Date:   
<asp:TextBox ID="txtEnd" runat="server">
</asp:TextBox> </div>

Next, from the toolbox drag over a Panel control and place it inside of the UpdatePanel and name it pCal. Within the Panel control you just implemented drag and drop a Calendar control inside of it and name it cal.

<asp:UpdatePanel ID="UpdatePanel" runat="server"> 
<ContentTemplate> 
<asp:Panel ID="pCal" runat="server"> 
<asp:Calendar ID="cal" OnSelectionChanged="cal_SelectionChanged" runat="server" Style="text-align: center"> </asp:Calendar> 
</asp:Panel> 
</ContentTemplate> 
</asp:UpdatePanel>

Highlight the every control on the page and center, justify them. The Design View should look like this:

Switch to your source view.

Within the calendar tag, add an OnSelectionChanged element.

<asp:Calendar ID="cal" OnSelectionChanged="cal_SelectionChanged" runat="server" Style="text-align: center"> </asp:Calendar>

Then locate the AJAX Toolkit and drag over two PopupControlExtender’s below and outside the UpdatePanel. Then add a TargetControlID and assign it the value txtBegin and txtEnd respectively. This allows the calendar control to place the value selected by the user inside of the specific textbox.

Next, add a PopupControlID for each PopupControlExtender and pass it the value pCal of the Calendar controlID. In this case you can position it at the Bottom.

<asp:PopupControlExtender ID="PopupCntrlEx1" TargetControlID="txtBegin" PopupControlID="pCal" Position="Bottom" runat="server" /> <asp:PopupControlExtender ID="PopupCntrlEx2" TargetControlID="txtEnd" PopupControlID="pCal" Position="Bottom" runat="server" />

The TargetControlID attribute provides the ID of the control tied to the extender. The PopupControlID attribute contains the ID of the popup panel. For this instance, both extenders show the same panel, but both panels are possible as well.

Save and Run. Now whenever you click within a text field, a calendar will appear, allowing you to select a date.

Next we need to add some logic to the code behind in order to populate the correct dates for the correct textbox. This is the reason that we added the OnSelectionChanged to the calendar control. Switch to your default.aspx.cs page and add this logic to the cal¬_OnSelectionChanged() event.

protected void cal_SelectionChanged(object sender, EventArgs e) 
{ 
if (txtBegin.Text == "") 
{ 
txtBegin.Text = cal.SelectedDate.ToShortDateString(); 
} 
else 
{ 
txtEnd.Text = cal.SelectedDate.ToShortDateString(); 
} 
}

The PopupControl is an ASP.NET AJAX extender that can be added to any control in order to open a popwindow that displays additional content, including ASP.NET server controls, HTML elements, etc. In this case, we made the popup window interactive within an ASP.NET AJAX UpdatePanel, this way it could be able to perform complex server-based processing (includeing postbacks) without affecting the rest of the page.

The post Learn how to use Multiple Popup Controls in ASP.NET 3.5 AJAX. C# appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/general/learn-how-to-use-multiple-popup-controls-in-asp-net-3-5-ajax-c/feed/ 0
Using the UpdatePanel Control in Visual Studio Web Developer 2010 /general/using-the-updatepanel-ajax-control-in-visual-studio-web-developer-2010/ /general/using-the-updatepanel-ajax-control-in-visual-studio-web-developer-2010/#comments Wed, 25 Sep 2013 18:00:21 +0000 /?p=378 Microsoft Server-Side AJAX Framework consists of one main control: the UpdatePanel Control. The UpdatePanel Control enables you to update a portion of a page without updating the entire page. In […]

The post Using the UpdatePanel Control in Visual Studio Web Developer 2010 appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
Microsoft Server-Side AJAX Framework consists of one main control: the UpdatePanel Control. The UpdatePanel Control enables you to update a portion of a page without updating the entire page. In other words it enables you to performance partial page rendering.

Step 1

Let’s open a new website and name it UpdatePanelSimple. Hopefully by now you will have remembered how to open a new website. If not you can check in the beginner tutorials.
The tag has two childtags – the ContentTemplate and the Triggers tags. The ContentTemplate tag is required, since it holds the content of the panel. The content can be anything that you would normally put on your page, from literal text to web controls. The Triggers tag allows you to define certain triggers which will make the panel update its content. The following example will show the use of both childtags.

Step 2

I have copied the code over and go ahead and copy it over to your source code as it looks.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="EmailForm.WebForm1" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>UpdatePanel Simple</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat ="server"/>
 
    Page Time: <%= DateTime.Now.ToString("T") %>
    <br /><br />
 
    <asp:UpdatePanel
        id="up1"
        runat="server">
        <ContentTemplate>
        UpdatePanel Time <%= DateTime.Now.ToString("T") %>
        <br />
        <asp:Button
            id="btn"
            Text="Update"
            runat="server" />
        </ContentTemplate>
    </asp:UpdatePanel>
           
    <div>
   
    </div>
    </form>
</body>
</html>

As you can see in the code or when switch over to design view you will see we have added a ScriptManager , and an UpdatePanel as well. The UpdatePanel contains a single Button Control, when you click the button only the content contained in the UpdatePanel control is refreshed.

The Page in the listing displays the current time both inside and outside the Update Control Panel Control. When you click the button, only the time within the UpdatePanel control is refreshed.

In our Next tutorial Regarding the Microsoft AJAX UpdatePanel we will take a more realistic approach that just begs for AJAX control over it.

The post Using the UpdatePanel Control in Visual Studio Web Developer 2010 appeared first on Ajax Tutorials, Tricks, and Code Examples.

]]>
/general/using-the-updatepanel-ajax-control-in-visual-studio-web-developer-2010/feed/ 0