Ajax removes any changes made my javascript - c#

Using ajax I am causing an OnTextChangedEvent before this happens there is some Javascript that performs a check on the input field for validation and outputs some text based on whether it is valid or not. The Ajax I run resets the changes made by my javascript. It all happens in this order:
Javascript fires!
Text changes show
Ajax fires!
Text changes reset
The ajax partial autopostback is contained in an update panel. Without giving any code away is there anyone who has an idea of a way to stop the javascript changes resetting?
Over the day I will add code as I find time. Thought I would get the question up atleast. Thanks in advanced.

The Text changes are made in the DOM-Model and are not transmitted to the server.
If the ajax fires it will override the changes in the DOM made by javascript.
Solution is to transmit the validation-texts to the server and to add them again via ajax.

An UpdatePanel completely replaces the contents of the update panel on
an update.
This means that those events you subscribed to are no
longer subscribed because there are new elements in that update panel.
Full answer here
In your Page or MasterPage, put the following script
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args)
{
Validate(); //method that performs check on input field
}
</script>

Related

onUploadComplete event of asyncFileUpload

how to display a btn after onUploadComplete event is executed? It's not coming now even I say btn.visible=true inside that event..
I read in one of the thread that this event happens asynchronously so we have to write javascript for it and call onClientUploadCompete.
But do anyone know how to do it withoiut writing javascript? please its urgent thanx in advance!
You've got two options - to execute client-side using JavaScript and AsyncFileUpload's OnClientUploadError and OnClientUploadComplete, or to handle the server-side UploadedComplete or UploadedFileError events fired by your AsyncFileUpload object.
If you choose client side, you can still include your Button as normal and include CSS for it to be display: none, which can be then altered in the JavaScript with something like the following:
$get(<%= AsyncFileUploaderInstanceName.ClientId %>).style.display = "block"
If you choose server side, you'll be able to refer to the .Visible property of whatever controls you like, and can alter them then. However, you'll have to update whatever UpdatePanel the button would be sitting in for the button to be rendered on the page.

ASP.net user control doesn't call a javascript function

I am developing asp.net web application, I have a repeater that call a registered user control, I have in the user control a button that I want to call a javascript function that make Ajax call to do some action on server. this button doesn't call the javascript method, I don't know why? and when I view source I found the javascript function is repeated for every item in the repeater, how to eliminate this repetition specially that I read server items inside the function, and why the function is not called?
Thanks a lot!
sercontrol.ascx
<div id="divBtnEvent" runat="server">
<input type="button" id="btnAddEvent" class="ok-green" onclick="saveEvent();" />
</div>
<script type="text/javascript">
function saveEvent()
{
var eventText = document.getElementById('<%=txtEventDescription.ClientID%>').value;
// make ajax call
}
Problem 1: In view source I found the javascript function is repeated for every item in the repeater.
Solution:
Put your js function on the page on which the user control is being called. You also have to place your js files references on your page not on user control.
Problem 2: You are trying to get control's value as <%=txtEventDescription.ClientID%>.
And I think, this control is on user control.
Solution: Please check your page source code and see that the control's actual clientid is.
If still have issues in calling js function, check firefox's Error consol.
Hope this help.
OP said and when I view source I found the javascript function is repeated for every item in the repeater
to get rid of it put ur javascript as follows
<head runat="server">
//heres goes ur js
</head>
I guess that's ur problem
Replace the saveEvent function definition from user control onto the page where the control is used. All the way as I understand, you have use in this function textbox id from that page.
Actually, if you have place javascript block in user control's markup it will be rendered along with the rest control's markup. To avoid this you may register javascript from the server code and check is that code block is already registered.
By the way, as it is - only the last function definition being taked into attention as it redefined the previous one each time new control instance rendered.

How do I generate JavaScript during an AJAX callback (postback) and then execute it on the browser?

In summary:
I have an ASP.NET web page that causes an AJAX postback to the server. When this event handler runs (in the code behind) it will generate some JavaScript that I then want to run in the client. Not sure how to achieve this.
In Detail:
I have an ASP.NET web page with multiple items displayed on the page.
As a "nice to have", I want to display either a green circle or a red cross next to each item (these differ depending upon each item). Since it isn't vital for the User to see these icons and also because it takes several seconds to work out which icon should be shown for each item, I want to perform this after the page has loaded, so in an AJAX callback.
My thought therefore was this. When creating the page, I would create both icons next to each object and create them with the style of "hidden". I would also make a note of each one's client ID.
Then, when the callback occurs, I fetch the necessary data from the database and then create a JavaScript function that changes the display for each of the icons I want to show from "hidden" to "visible".
I thought I could achieve this using the ScriptManager object.
Here's a very trivial version of my server side code (C#)
void AjaxHandler(object sender, EventArgs e)
{
// call to database
string jscript = "alert('wibble');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript);
}
Obviously, here I'm just trying to get an alert to fire after the postback has occurred...in real life I'd have my JavaScript function to change the display of all the icons I want to display.
When I run this, the serverside code runs and yet nothing happens in the server.
I have also tried:
ScriptManager.RegisterClientScriptBlock()
Page.RegisterStartupScript()
Page.RegisterClientScriptBlock()
Page.ClientScript.RegisterStartupScript()
Page.ClientScript.RegisterClientScriptBlock()
but none of them work....
FireFox shows the following JavaScript error:
Error: uncaught exception: [Exception... "Node cannot be inserted at the specified point in the hierarchy" code: "3" nsresult: "0x80530003 (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)" location: "http://localhost/MyWebSiteName/Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=ctl00_RadScriptManager1_TSM&compress=1&_TSM_CombinedScripts_=%3b%3bSystem.Web.Extensions%2c+Version%3d3.5.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3d31bf3856ad364e35%3aen-US%3a3de828f0-5e0d-4c7d-a36b-56a9773c0def%3aea597d4b%3ab25378d2%3bTelerik.Web.UI%2c+Version%3d2009.3.1314.20%2c+Culture%3dneutral%2c+PublicKeyToken%3d121fae78165ba3d4%3aen-US%3aec1048f9-7413-49ac-913a-b3b534cde186%3a16e4e7cd%3aed16cbdc%3a874f8ea2%3af7645509%3a24ee1bba%3a19620875%3a39040b5c%3af85f9819 Line: 1075"]
Does anyone know if what I am trying to do is even allowed?
If not - what's my alternative?
Thank you
Since your script doesn't have enclosing <script> tags, you need to use this form of RegisterStartupScript:
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript, true);
You said your initial goal was:
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Here's a way you can do that:
given:
<asp:ScriptManager runat="server" ID="scriptManager">
</asp:ScriptManager>
<script type="text/javascript">
function endRequestHandler(sender, args) {
var dataItems = args.get_dataItems();
for(var key in dataItems){
if(/^javascript:/.test(dataItems[key])){
eval(dataItems[key].substring("javascript:".length));
}
}
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
</script>
<asp:UpdatePanel runat="server" ID="pnl">
<ContentTemplate>
<asp:Button runat="server" ID="btnClick" Text="Click me!" OnClick="btnClick_Click" />
</ContentTemplate>
</asp:UpdatePanel>
You can create a click handler that does this:
protected void btnClick_Click(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterDataItem(this, "javascript:alert('hello world!');");
}
What's happening is during the postback, the page request manager is sent a data item your code-behind. That data-item happens to be a javascript command. After the postback, the client side script manager's endRequest handler is checking for data items. Normally you'd want to see who those items are for, which is apparent by the key of the item (it's the client ID of the control that is the target of the data being sent). In your case, you could load this up with the javascript that you want to fire, tell yourself that it's a javascript because it's prepended, then dynamically evaluate the script.
So in this example, clicking the "Click Me!" button will generate a Hello World prompt whose script was actually created by the code-behind during the postback.
You'll have to be very cautious with this approach until you're comfy - I'd avoid references to "this"...
Happy coding.
B
Okay
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Couldn't get that to work....
I got around this in the following way:
When the page loads, data is sent (AJAX) to the server. This processes the data and serialises the results updating a hidden text element, which goes back to the browser. Meanwhile, I have a JavaScript timer on the page that runs a JavaScript function that was generated when the page first loads. This function looks at the hidden text element. If that element has text (the result of the postback) then it shuts down the timer, deserialises the data and then works out how to update the page.

Javascript timer

I have a set of objects and each those object keep track of some strings.
Those objects are created at page load and stored in an object array.
I have four user controls in ascx file that displays those strings of a particular object at a time.
And also I have a play button in the same ascx file which is default set to play.
When I load the ascx it displays the first set of strings in a particular object.
And after 5 second time interval iy should display the second set of strings in the next object. When the play button pushed, it should move into pause state also.
Can anybody give me a start to achieve this requirement. my code behind file is C#
Fundamentally, you want a 'Slideshow' of your ASCX controls. A common way to do this is by having all your ASCX's visible and then use Javascript and CSS to make one visible at a time.
Google for 'html css javascript slideshow'.
http://www.catswhocode.com/blog/top-10-javascript-slideshows-carousels-and-sliders
Just realised you might want to achieve this via front-end JavaScript as per your question title? In which case, you will need the setInterval function, and your array of data available in the DOM.
Suppose your button is
<asp:ImageButton src="source.jpg" class="btnPlay" alt="Play" />
Your JavaScript (using jQuery) could be along the lines of:
$(function() {
$('.btnPlay').click(function() {
$(this).toggleClass('btnPause');
if($(this).hasClass('btnPause') {
yourHandlerID = setInterval ("yourHandler()", 5000 );
} else {
clearInterval (yourHandlerID);
}
});
});
You can also do this via C# code behind using the timer class, example like:
http://www.csharphelp.com/2006/02/c-timer-demo/
And everytime the timer triggers the event handler you define, you can reiterate through your array, display what you want.
The toggle pause button would be just stopping the timer.
Microsoft reference:
http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.71).aspx

c# Ajax Lazy Loading

I need to populate 4 GridViews on an aspx page, but I only bind a datatable to one of them on page load. I need to pupulate the other 3 after page load.
does anyone know the best way to do this using ajax ?
Currently I'm using javascript to __doPostBack on a button that pupulates the 3 GridViews but unfortunately this forces a full page load even when using an update panel. I need the page to load, and then populate the GridViews as the datatables are returned.
any suggestions would be much apreciated.
The way you are doing it should work ok, although using jquery to populate a div via the $("#targetDiv").load("contentUrl"); function may be a cleaner way to do it. Anyway, in order to get your current implementation working, there could be a few things you want to look at:
I assume EnablePartialRendering is true on your ScriptManager (always worth checking!).
Make sure the eventTarget for the __dopostback call is set up as an async trigger for your update panels or that it is inside the UpdatePanel if you are only using one UpdatePanel. (See here for details)
Try returning false from the javascript code that executes in the onclick event handler if you have attached this to a button, to make sure the form is not being submitted normally by your browser when you click the button.
If I understand the question properly, you want the data to load after the page is in the browser. If this is the case, then you can fire an event with JavaScript when the page loads on the client.
One method I've used is to put a hidden (with CSS, not any property) button on the page and 'clicking' it with javascript. The event of the button click event will need to be wired in the page's code. Also the button would have to be in an update panel that either contains the grids you want to be bound or has the appropriate triggers to cause them to reload.
You might look at JQuery to get manage when this code gets fired. The $(document).ready(function(){ /* Your code here... */ }); method will fire after the entire DOM is available, which is faster than waiting on the entire page to load (images and so forth).

Categories

Resources