Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Tuesday, April 7, 2009

Trigger Html/Javascript Event from Javascript

In many situation i had to trigger JavaScript Event from code. Like click on a button when something happened to post the page. It mainly comes into picture when i use UpdatePanel or using modalpopup for click on a button inside grid/list/gridview ect. This creation of event is very much dependent on the browser. Here is the code to trigger a button click event
function clickButton()
{
if( document.createEvent )
{
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent( 'click', true, false, window, 0, 12, 345, 7, 220, false, false, true, false, 0, null );
$(' btnTransRefresh').dispatchEvent(evObj);
}
else
if( document.createEventObject )
{
$('btnTransRefresh').fireEvent('onChange');
}
}

Here i am using Prototyprjs framework, so you see the "$". You can replace those with document.getElementById('') syntax.
initMouseEvent takes the following parameters.
initMouseEvent( 'type', bubbles, cancelable, windowObject, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget )

In many scenarios we do some javascript calculation on change of value in some particular textboxes. But in some scenarios, the value in the textbox on change of which we need to calculate is done through some javascript. Like in my project i was using calender from ajax control toolkit which is inside a project specific control names PRPCalender. In some pages i had to do some calculations only when the value in calender is changed. So i could not use the javascript events associated with the calender control (ajax). So i decided to go with triggering onchange event as the textbox showing the calender control doesn't fire the onchange event as the value is changed through JavaScript.
string methodName = "prpCalenderDateChanged" + txtCalendar.ClientID;
calendarExtender.OnClientDateSelectionChanged = methodName;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat(@"
function {0}(sender,eArg)
{{
//alert('Calender Date Changed');
var tbId = '{1}';
//$(tbId).blur();
//$(tbId).focus();
if( document.createEvent )
{{
var evObj = document.createEvent('HTMLEvents');
evObj.initEvent( 'onchange', true, false);
$(tbId).dispatchEvent(evObj);
}}
else
if( document.createEventObject )
{{
$(tbId).change();
}}
}}
", methodName, txtCalendar.ClientID);
ScriptManager.RegisterStartupScript(this, this.GetType(), "textChanged" + txtCalendar.ClientID, sb.ToString(), true);
Here inside my calender control PRPCalender, i am registering a function which is unique for each calender control inside any page (i am using the client id as concatined to generate the method name) which fires the onchange event on the textbox.
calendarExtender.OnClientDateSelectionChanged = methodName;
which is called by toolkit JS when the date value is changed.
Some Useful Link Link1

Tuesday, July 8, 2008

Use PageRequestManager To Trigger Javascript for Asynchronous Postback

In my last post Send Balk Data(Datatable) From Child Window To Parent
i explained how we can send bulk data from child window to parent. But if we are using Asp.Net ajax in client page i.e the postback is caused asynchronously, then we can't use the RegisterStartUpScript to call the javascript function. But instead we have to use the Microsoft's Ajax javascript framework. I did this with the use of PageRequestManager JS Class as follows

var postBackThroughAdd = false;
function addRequestManager()
{
var reqMgr=Sys.WebForms.PageRequestManager.getInstance();
reqMgr.add_beginRequest(
function()
{
//Do something before the call begins
}
)
reqMgr.add_endRequest(
function(sender,args)
{
if (args.get_error() == undefined)//Checks there is no error
{
if(postBackThroughAdd)
{
postBackThroughAdd = false;
addToQuote();
//Function to trigger the parent postback and flag set and close the page
}
}
}
)
}

Variable postBackThroughAdd is a flag variable, which is set "true" when the button for which we want to send the data to parent is clicked. The code is like

<asp:Button ID="btnAddPartNoToCatalog" runat="server" Text="Add" CssClass="formButton"OnCommand="btnAddPartNoToCatalog_Command" OnClientClick="postBackThroughAdd = true;" />

Here if any error occurs while setting the data in session through server event btnAddPartNoToCatalog_Command, i am simply throughing the error with some userfriendly message. The message will be shown in JS message box and args.get_error() will not be undefined. So the function addToquote() will not be called.
Note: addRequestManager() function should be called on bodyload so that the JS events are registered before they fires actully. With the help of PageRequestManager class you can do some other tasks like showing some message in div after some action has succeeded of failed, show/hide loading... div without using UpdateProgress but same functionality(In the beginRequest handler, set the div's "display" property to "block" and int endRequest hander display to "none").

Friday, July 4, 2008

Send Balk Data(Datatable) From Child Window To Parent

Currently in one of my .aspx page i was selecting some information from a child window which is opened from a parent window. I opened the window like
window.open('PartNoLookup.aspx','PartNo','left=150, top=60,width=800,height=600, toolbar=no, status=1,scrollbars=yes,resizable=no,dependent=yes');
Some PartNos with their information was selected by the child "PartNoLookup.aspx" page. Now i have to send the part nos to the parent page to be displayed. My parent page was NewQuote.aspx.
Now the problem arises if it was a small value then i could do it with
window.opener.document.getelementById('parentCtrlId').value='Some Value'
But as it was a bulk datatable i can't send it like that.
I stored the DataTable in Session["PartNo"] from the child page. And placed a hidden field "hidFlag" (not with runat='server'. this should be a html hiddenfield) in the Parent Page (i.e. NewQuote.aspx). And wrote some javascript with the Page.ClientScript.RegisterStartupScript like
Page.ClientScript.RegisterStartupScript(typeof(string), "", "refreshParentAndClose();", true);
And inside childpage (PartNoLookup.aspx) i added the JS function refreshParentAndClose() as
function refreshParentAndClose()
{
window.opener.document.getelementById('parentCtrlId').value='checksession'
window.opener.document.forms[0].submit();
window.close();
}
So this function will set the flag in the parent a also submit the page.
Here as the page is postback by some unconventional way, only the PageLoad,PreRender and some processing cycle events will fire in the parent. So i have to check for the flag inside tha Load() event. So i added the checking code in Page_LoadCode as
if(Request.Form["hidFlag"]!=null)
{
string flag=Request.Form["hidFlag"];
switch(flag)
{
case "checksession":
//Check the session and show inside the page.
break;
}
}

Note:Put the hidden field as Html hidden, not with runat=server coz, if you set it server variable then change by the javascript will no be visible as it will be restored from the viewstate. y JavaScript we are changing the value not the stored value inside Encripted ViewState. Also if you use server Hidden field the clientid may not be same as server id. So setting it from child page will be problemetic (but not impossible).

Tuesday, April 1, 2008

Ajax Like File Uploading

Place a hiddenIFrame into the page and submit the form containing the file uploader (input type='file') to the hidden iframe by changing the target property of the form to the name of
the IFrame. Here i have made the target of form (id='formUpload') to "iframeHidden"
as my iframe name is "ifameHidden". For uploading the file you have to make the'
enctype' and 'method' attributes values as it is in the example.

I have made the action attribute of the page to UploadFile.aspx page. This is a
page where it counts the Files Collection of the Request Object and if it finds
any file in the Collection (Request.Files.Count>0), it saves the file in the same
folder with the same name as file. The saving code is very trivial, for a real world
applicatio you have to be carefull while saving like name overwrite,different path
ect.



<script type="text/javascript">
function uploadFile(id)
{
document.getElementById("formUpload").submit();
}
</script>



<iframe id="iframeHiden1" style="height:0px;width:0px;border:0"
name="iframeHiden" src="UploadFile.aspx"></iframe>

<form id="formUpload" target="iframeHiden" enctype="multipart/form-data"
action="UploadFile.aspx" method="post">


Ajax Upload File In HTML Form:<input type="file" onchange="uploadFile('file1')"
id="file1" name="fileUploadHTML" />


</form>


UploadFile.aspx Page Load Event


protected
void Page_Load(object sender, EventArgs e)

{



int noOfFile = Request.Files.Count;


if (noOfFile > 0)


{


string path = Request.PhysicalPath.Substring(0, Request.PhysicalPath.LastIndexOf("\\")
+ 1) + Request.Files[0].FileName;


Request.Files[0].SaveAs(path);


}
}