Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for the ‘Javascript’ Category

Blogs releted to javascript

LINQ expressions with javaScript!

Posted by Viral Sarvaiya on April 7, 2015


Hello All, after a long time..

I get very useful link which I like to share with you all.

Being a web developer and using javaScript everyday, Now more than ever javaScript is exploding in its usage.

we can use linq in javascipt. surprised? click here to learn more about that.

Thanks.

Advertisements

Posted in ASP.NET, Javascript | Tagged: , | Leave a Comment »

Using Jquery detect mobile

Posted by Viral Sarvaiya on October 22, 2013


Toay i get good script of jQuery that detect mobile.

It require to Jquery file – http://code.jquery.com/jquery-1.8.3.js

Here code is.

$(document).ready(function () {
  var isMobile = {
    Android: function () {
      return navigator.userAgent.match(/Android/i) ? true : false;
    },
    BlackBerry: function () {
      return navigator.userAgent.match(/BlackBerry/i) ? true : false;
    },
    iOS: function () {
      eturn navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
    },
    Windows: function () {
      return navigator.userAgent.match(/IEMobile/i) ? true : false;
    },
    any: function () {
      return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
    }
  };
  alert(isMobile.any())
});

Hope it helps you.

Thanks.

Posted in Javascript, Jquery | Tagged: , , , , | Leave a Comment »

Export to Excel using jQuery

Posted by Viral Sarvaiya on October 21, 2013


From my past posts explains how to export to excel as
1. Export GridView Data into CSVFile In Asp.net
2. GridView Export to Excel

So here its 3rd type to export to excel using Jquery.

In javascript, we have window.open function. We are using same function to export to excel using jquery.

Syntax,

window.open(MIMEtype,replace);

Here
MIMEtype : this is the optional parameter, and its for type of document. default it take as “text/html”
replace : this is also optional parameter, and its set.

Example,

$("#btn_Export").click(function(e) {
window.open('data:application/vnd.ms-excel,' + $('#divData').html());
e.preventDefault();
});

Hope its helps you.

Thanks.

Posted in .Net, ASP.NET, Javascript, Jquery | Tagged: , , , , , | Leave a Comment »

Use of Cookies in jQuery

Posted by Viral Sarvaiya on September 27, 2013


I have already writen that how to use cookies in asp.net and silverlight from below post
https://codesimplified.com/2009/09/10/how-to-createreaddelete-cookies-in-asp-net/
and
https://codesimplified.com/2010/08/27/cookies-in-silverlight/

here i am posting new post that shows how to use cookies in Jquery

Create cookie:

$.cookie('myCookie', 'CookieValue', { expires: 7, path: '/' });

Read cookie:

$.cookie('myCookie'); // => "CookieValue"

Read all available cookies:

$.cookie(); // => { "myCookie": "CookieValue", "...remaining": "cookies" }

Delete cookie:

// Returns true when cookie was found, false when no cookie was found...
$.removeCookie('myCookie');

// Same path as when the cookie was written...
$.removeCookie('myCookie', { path: '/' });

Thanks.

Posted in .Net, ASP.NET, Javascript, Jquery | Tagged: , , , , , | Leave a Comment »

Detect browser F5 / refresh and X / Close in javascript

Posted by Viral Sarvaiya on May 8, 2012


Below javascript is use to detect wether browser is refereshed or closed.

window.onunload = function (e) {
// Firefox || IE
e = e || window.event;
var y = e.pageY || e.clientY;

if (y < 0) {
alert("close");
}
else {
alert("refresh");
}
}

Thanks.

Posted in ASP.NET, Javascript, Silverlight | Tagged: , , , , , | 2 Comments »

Window Close Event of Browser

Posted by Viral Sarvaiya on April 12, 2011


hi,

recently i get a problem that what if some user accessing my website and close directly browser without logout from the system?

i get good solution with this but this is not 100% secure.

for that we have 2 events in javascript “onbeforeunload” or “onunload”

but onunload event is not working in firefox and some time in IE8 also, so onbeforeunload is suitable for both.

<html>
<head>
<title>Window Close Event of Browser</title>
<script language="javascript" type="text/javascript">
 function CloseBrowser() {
 alert("Browser is closing");
 }
 </script>
</head>

<body onbeforeunload="CloseBrowser();">

</body>
</html>

 

window.onbeforeunload = function() {
    return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...
 };

 
As we have already discussed that there is no 100% fool proof way to detect the browser close event in a lot of cases, the above technique can fail. For example if the user kills the browser’s process from task manager, there could be many more cases. Yet in a lot of cases, this technique can be handy.

Best of luck and happy programming.

Thank you.

Posted in ASP.NET, Javascript | Tagged: , , , , , | Leave a Comment »

Redirect to a New Page using JavaScript

Posted by Viral Sarvaiya on October 16, 2010


An easy way to redirect a user to a new Page using JavaScript is to use


window.location = "http://www.devcurry.com";

However the problem with this approach is that it adds an item to your browser history. So in browsers like IE, the user can access the history by hitting the back button, which can be confusing to users, as they will redirected back and forth.

 

If you want to avoid the back button, use ‘window.location.replace’ which loads the new page and replaces the current page in the user’s History, with the new one, as shown below:


<head>
 <title>Redirect to a New Page</title>
 <script type="text/javascript">
 window.location.replace("http://www.devcurry.com");
 </script>
</head>
<body>

Now when you are redirected to the new page, there is no back button.

For More Details Click Here

Posted in ASP.NET, Javascript | Tagged: , , , | Leave a Comment »

How To Get URL Parts in JavaScript

Posted by Viral Sarvaiya on April 27, 2010


This JavaScript tutorial article concentrates on:

  • Obtaining the URL from the window.location object
  • Changing the current location with window.location.href and window.location.reload
  • Splitting and rebuilding URLs with Array and String splitting functions

The first step is understanding the JavaScript Location object.

The Location Object

This is a JavaScript class that is used to store URLs. It comes with properties that represent each part of the URL, and can be updated by changing the href property. The key properties that this article deals with are:

  • location.href : the full URL
  • location.protocol, location.host & location.pathname : the parts of the URL

In addition there are various methods that

  • location.reload
  • location.replace

These shall be discussed with reference to the window.location object.

The window.location Object

The window.location object is the specific object that stores the URL of the currently loaded page. If a JavaScript function changes the window.location.href property, then the page should reload with the new location.

However, this may not always be the case, and so the location.reload and location.replace methods have also been provided in the Location object. These were introduced in JavaScript 1.2, and give a little more control over the way that browsing history and current page location URLs are handled. In some cases it may not be enough to set the window.location.href, and so calling window.location.reload will force the page to be refreshed.

The window.location.replace method is used to overwrite the history entry in the browser, for the current page.

Splitting and Rebuilding URLs

The URL is stored as the following parts:

protocol://host/pathname

Each part can be accessed using the appropriate property of the Location object:

  • location.protocol : for web pages, the value http
  • location.host : for this site http://www.suite101.com
  • location.pathname : the path to a page i.e. mypages/page1.html

It is important to note that:

  • The protocol is store without the : or // that make up the whole URL
  • The host will contain a port, where appropriate
  • the pathname does not contain the leading /

So, to rebuild a URL based on the above information, code such as the following can be used:

newURL = window.location.protocol + "//" +  window.location.host + "/" + window.location.pathname;

This makes it very easy to create inline links that are context sensitive, and that refer pages that should exist on the server. For example, a site might have a tag page that collects all content that has the tag marketing associated with it. If the word marketing were to appear in a block of text, then JavaScript could be used to pre-process that block of text, and add a URL based on the current URL, but containing the reference to the marketing tag page.

One final note is that the pathname will be a / separated string, which can be split into an array of strings using the following code:

pathArray = window.location.pathname.split( '/'  );

Using this approach, it is easy to rebuild URLs, as each component will be contained in one array element. Again, however, it is necessary to put the / back:

newPathname = "";
for ( i = 0; i pathArray.length; i++ ) {
newPathname += "/";
newPathname += pathArray[i];
}
you can also retrieve the full path within code
Uri MyUri = Request.Url;

String Temp = MyUri.Scheme + @"://";
Temp = Temp + MyUri.Host;
Temp = Temp + Request.ApplicationPath;

Posted in ASP.NET, Javascript | Tagged: , , , , | 2 Comments »

Reading XMl file from Javascript in asp.net C#

Posted by Viral Sarvaiya on March 23, 2010


hi here i demonstrate another application which read the XML file from the javascript,

in my previous post, i demostrate the webservice calling from javascript, this post i continue from that,

web service  return the string which is in XML format and javascript read this XML string and give the alert according to the TAG of the XML.

follow the steps as per the my previous post url : https://viralsarvaiya.wordpress.com/2010/03/23/calling-web-service-from-java-script-in-asp-net-c/

we repeat the Steps,

step 1 : file -> new -> web site

step 2 : select ASP.NET Web Service

step 3 : Add new web form name “default.aspx”

Step 4 : following code shows the “service.cs” file which is the web service file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml ;
using System.IO ;

[WebService(Namespace = "http://Localhost...xys/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class MyService : System.Web.Services.WebService
{
public MyService()
{

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld(string strNoOfData)
{
// Create the xml document containe
XmlDocument doc = new XmlDocument();// Create the XML Declaration, and append it to XML document
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("PHI_Data");
doc.AppendChild(root);

int iNoOfData = 0 ;
if ( int.TryParse( strNoOfData, out iNoOfData ) == false )
iNoOfData = 600 ;

DateTime dtTemp = new DateTime(2009, 1, 1, 12, 0, 0);
Random rndTemp = new Random();

float fValue = ((float)rndTemp.Next(1000, 2000)) / 100;

for (int iCounter = 0; iCounter < iNoOfData; iCounter++)
{
XmlElement Data = doc.CreateElement("PHI_Record");
Data.SetAttribute("Record_Number", iCounter.ToString());

XmlElement dataTimeStamp = doc.CreateElement("TimeStamp");
dataTimeStamp.InnerText = dtTemp.ToString("yyyy-MMM-dd hh:mm:ss");
XmlElement dataValue = doc.CreateElement("Value");
dataValue.InnerText = fValue.ToString();
Data.AppendChild(dataTimeStamp);
Data.AppendChild(dataValue);
root.AppendChild(Data);

fValue = ((float)rndTemp.Next(1000, 2000)) / 100;
dtTemp = dtTemp.AddHours(1);

}
string xmlOutput = doc.OuterXml;

return xmlOutput;
}
}

step 5 : following code shows the “default.aspx” file

</pre>
<head id="Head1" runat="server">
<title>Read XML File From Javascript with Web Serice in asp.net</title>

<script type="text/javascript">

function CallService() {
MyService.HelloWorld(document.getElementById('Textbox1').value, OnComplete, OnError, OnTimeOut);
}

function OnComplete(xmlText) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlText);

var child = xmlDoc.documentElement.firstChild;
while (child) {
alert(child.firstChild.text);
alert(child.lastChild.text);
child = child.nextSibling;
}
}

function OnTimeOut(arg) {
alert("timeOut has occured");
}

function OnError(arg) {
alert("error has occured: " + arg._message);
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<fieldset>
<asp:TextBox ID="Textbox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Call Service" OnClientClick="CallService()" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>

Step 6 : Run The Application Enjoy Coding…

Posted in ASP.NET, Javascript | Tagged: , , , , , , | Leave a Comment »

Calling Web Service from Java script in asp.net c#

Posted by Viral Sarvaiya on March 23, 2010


Here i m demonstrate the simple application that calling webservie from javascript

step 1 : file -> new -> web site

step 2 : select ASP.NET Web Service

step 3 : Add new web form name “default.aspx”

Step 4 : following code shows the “service.cs” file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://Localhost...xys/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]

<strong>[System.Web.Script.Services.ScriptService()]</strong>

public class Service : System.Web.Services.WebService
{
public Service () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld(string strNoOfData)
{
return strNoOfData;
}

}

step 5 : following code shows the “default.aspx” file


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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></title>
<script type="text/javascript" language="javascript">
function CallService() {
Service.HelloWorld(document.getElementById('Textbox1').value, OnComplete, OnError, OnTimeOut);
}

function OnComplete(Text) {
alert(Text);
}

function OnTimeOut(arg) {
alert("timeOut has occured");
}

function OnError(arg) {
alert("error has occured: " + arg._message);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service.asmx" />
</Services>
</asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<fieldset>
<asp:TextBox ID="Textbox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Call Service" OnClientClick="CallService()" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

Step 6 : Run The Application

Enjoy Coding…

Posted in ASP.NET, Javascript | Tagged: , , , | 4 Comments »

 
%d bloggers like this: