Settimeout() javascript function is ignored - javascript

i have a simple button in my aspx page:
<asp:Button ID="a1" runat="server" OnClientClick="test2();" />
and the javascript function is:
function test2() {
setTimeout("alert('hello')", 1250);
}
The SetTimeout is totaly ignored - the alert won't show and the timer won't wait.
i read about 10 posts about this problem on ths site , none of the solutions work.
i tried calling another function instead of the alert function, i tried calling function with parameters using the function(){..}.
i also tried calling the Settimeout straight from the OnclientClick function :
OnClientClick="setTimeout('alert(\'hello\')',1250);"
nothing works, the Settimeout is ignored!
i'm using ie9.

Please try:
window.setTimeout(function () { alert('hello'); }, 1250);

The JavaScript worked fine. The page just looks the same, and the javascript just looks like it didn't work, but everything is working as designed.
Here's what’s happening...
User clicks the button.
The JavaScript is executed. The settimeout is set and starts to time.
The runat="server" now posts to the server (however the timeout was still ticking down)
Code for the objects OnClick event is run at the server (the page is being rebuilt server side).
A new response stream is sent to the client browser.
The client browser catches it and renders the "new" page resetting javascript for the new page (this is the new ASPX page you asked for!).
So even runat="server" on a different form element will stop both settimeout or setinterval methods from finally executing.
IMO a better way to code is to use AJAX on the client side to post up values to your server, catch them on a page at the server, build your html or javascripts and send them back to the client browser to catch and either replace the innerHTML of an element id or eval the javascript... less overhead, faster, better, more graceful and far more control . You can use stringbuilder if your using .NET to build the HTML fragments as this is far faster than multiple string concatenations.
hope this helps.

It's 100% Working Try this..
$(document).ready(function () {
$('#<%= DoesNotwork.ClientID %>').click(function (e) {
e.preventDefault();
setTimeout(function () {
alert("Hello");
$("form").submit();
},
3000);
});
});

Related

Re-execute js on back without reloading the whole page

Is there a way to re-execute JS without refreshing a page?
Say if I have a parent page and an inside page. When the inside page gets called, it gets called via ajax, replacing the content of the parent page. When user clicks back, I would like to navigate them back to the parent page without having to reload the page. But, the parent page UI relies on javascript so after they click back, I would like to re-execute the parent page's javascript. Is this possible?
Edit: Here is some code. I wrap my code in a function but where and how would you call this function?
function executeGlobJs() {
alert("js reload success");
}
You could use the html5 history-api:
In your click-handler you'll call the pushState-method, stat stores the current state for later reuse:
$(document).on('click', 'a.link', function () {
// some ajax magic here to load the page content
// plus something that replaces the content...
// execute your custom javascript stuff that should be called again
executeGlobJs()
// replace the browser-url to the new url
// maybe a link where the user has clicked
history.pushState(data, title, url);
})
...later if the user browses back:
$(window).on('popstate', function () {
// the user has navigated back,
// load the content again (either via ajax or from an cache-object)
// execute your custom stuff here...
executeGlobJs()
})
This is a pretty simple example and of course not perfect!
You should read more about it here:
https://css-tricks.com/using-the-html5-history-api/
https://developer.mozilla.org/en-US/docs/Web/API/History_API
For the ajax and DOM-related parts, you should need to learn a bit about jQuery http://api.jquery.com/jquery.ajax/. (It's all about the magic dollar sign)
Another option would be the hashchange-event, if you've to support older browsers...
You can encapsulate all your javascript into a function, and call this function on page load.
And eventually this will give you control of re-executing entire javascript without reloading the page.
This is common practise when you use any concat utility (eg. Gulp)
If you want to reload the script files as if it would be on a page reload, habe a look at this.
For all other script functions needed, just create a wrapper function as #s4n989 and #Rudolf Manusadzhyan wrote it. Then execute that function when you need to reinit your page.
I'm having the same problem I don't use jquery.
I don't have a solution yet. I think that your problem is that it doesn't read all the document.getelements after you add content, so my idea is to put all the element declarations in a function. And than after the ajax call ends to call the function to get all the elements again.
So it might be something like that
Func getElems(){
const elem= document.getelementsby...
Const elem.....
At the end of the js file make a call for
the function
getelems()
And than at the end of the event of the
ajax call. Just call the function again.
Sorry that is something that comes to my mind on the fly while reading and thinking on the problem i have too:).
Hope it helped I will try it too when I will be on the computer :)
I believe you are looking for a function called
.preventDefault();
Here's a link to better explain what it does - https://api.jquery.com/event.preventdefault/
Hope this helps!
EDIT:
By the way, if you want to execute the JS on back you can wrap the script inside of
$('.your-div').on('load', function(e) {
e.preventDefault();
//your JavaScript goes here
}

Clicking a link does not refresh the content

I've been looking at how to automate actions on a webpage with PhantomJS, however I'm having issues manipulating the page to do what I want it to.
I'm using this as test site. I've managed to get Phantom to open the webpage and scrape the random sentence from the #result span. But now what I want to do is get another sentence without re-launching the script. I don't want to close and re-open the page as Phantom takes ages to launch the webkit and load the page. So I thought I could get another sentence by getting Phantom to click on the 'Refresh' button below the sentence box. Here's what I have at the moment:
var page = require('webpage').create();
console.log("connecting...");
page.open("http://watchout4snakes.com/wo4snakes/Random/RandomSentence", function(){
console.log('connected');
var content = page.content;
var phrase = page.evaluate(function() {
return document.getElementById("result").innerHTML;
});
console.log(phrase);
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
$("frmSentence").click();
});
});
var content = page.content;
var phrase = page.evaluate(function() {
return document.getElementById("result").innerHTML;
});
console.log(phrase);
phantom.exit();
});
As you can see I'm trying to click the refresh button by using a .click() function, but this isn't working for me as I still get the same sentence as beforehand. Given the HTML for the button:
<form action="/wo4snakes/Random/NewRandomSentence" id="frmSentence" method="post" novalidate="novalidate">
<p><input type="submit" value="Refresh"></p>
</form>
I'm not sure what I should be referencing in the script to be clicked on? I'm trying the form ID 'frmSentence' but that isn't working. I'm wondering if .click() is the right way to go about this, is there some way for Phantom to submit the form that the button is linked to? Or maybe I can run the associated script on the page that gets the sentence? I'm a bit lost on this one so I don't really know which method I should go with?
You have a problem with your control flow. page.includeJs is an asynchronous function. If you have some other statements page.includeJs, they are likely executed before the script is loaded and the callback is executed. It means in your case that you've read the sentence 2 times before you even trigger a click.
If you want to do this multiple times, I suggest to use recursion since you cannot write this synchronously. Also, since you want this to be fast, you cannot use a static setTimeout with a timeout of 1 second, because sometimes the request may be faster (you lose time) and sometimes slower (your script breaks). You should use waitFor from the examples.
Instead of loading jQuery every time, you can move page.includeJs up and include everything else in its callback. If you only need to click an element or if jQuery click doesn't work (yes, that happens from time to time), you should use PhantomJS; click an element.
web scraping is about sending require information to a web server and get the result. It is not about behaving like a user clicking button or entering search criteria.
All you need to do in this example is send a POST request to http://watchout4snakes.com/wo4snakes/Random/NewRandomSentence. The result is just text in page.content, it does not even need to evaluate. So to get more than one sentence you just need to do a loop of page.open

Call JavaScript Function On Call Behind of Javascript before redirecting to another page

I have Javascript function which i need to call at code behind in vb.net. The Main problem is it is not called properly because there is redirection to next page before this function executes. I do not want to call this function on Onclick event of button or something like that i want to call it after some specific condition in code behind. I have already tried following solutions please let me know if you have some other suggestions.
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, Me.GetType(), "Script", "ShowEntryPermForm();", True)
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Window", "ShowEntryPermForm();", True)
Problem Description: added from comment
The scenario is that in javascript function i have checked various conditions related to the project and it open up a pop up window where user enter his or her comments.
It is not necessary every time the function will open the pop up window. But by default the page redirects to new page as both the functions Javascript and redirection to another window are run on click event of the button.
But now my requirement is changed now i have to call the function from code behind in particular condition. Hope you get it now
You can do this in following way.
window.onbeforeunload = function()
{
//your code goes here
return "";
}
If you return anything here then browser will display and ask user whether to leave the page. In your case you don't need to return anything but runs the code.
The only way is to Separate the code and javascript in the way they will not rely on each other
for example you make an hidden asp:button with the rest of server side code
server side :
if(...) then
page.ClientScript.RegisterStartupScript(Me.GetType(), "Window", "ShowEntryPermForm();", True)
else
page.ClientScript.RegisterStartupScript(Me.GetType(), "Window", "otherfunction();", True)
end if
sub IDServersideHiddenbutton(obj as object ,e as eventargs)handles IDServersideHiddenbutton.click
rest of the server side code including the redirect
end sub
client side :
javascript ShowEntryPermForm()
{
// javascript code
$("#IDServersideHiddenbutton").click();
}
javascript otherfunction()
{
//just the click
$("#IDServersideHiddenbutton").click();
}
I really don't know your code structure but You can manipulate it to work with this idea

Calling Jquery whilst partial postback on updatepanel

I have a very strange issue on Jquery and partial postback on updatepanel.
What I have done is created a jquery logic in code behind and used :
Page.ClientScript.RegisterStartupScript(this.GetType(), "jsSlider" + select.ClientID, sb.ToString());
to create the Jquery Slider feature in a repeater. However Whats happening is when I put this within inside updatepanel it runs ok and the jquery slider works however any partial postback and I lose my lovely jquery slider feature because I need to re-bind the slider feature back after each partial postback.
How can I do this using similar code like Page.ClientScript.RegisterStartupScript(this.GetType(), "jsSlider" + select.ClientID, sb.ToString());
Is there another way to say Page.ClientScript.EVERYPOSTBACK(this.GetType(), "jsSlider" + select.ClientID, sb.ToString()); or something?? I am open to other suggestions?
you can use the "pageLoad" function in your javascript on your front end code. The pageLoad function gets called on the initial pageload and after every partial postback. If there are things that only need to be called on the initial page load, you would still want to put them in document ready.
<script type="text/javascript">
function pageLoad()
{
//...
//anything you want to happen every time the page loads or after a partial postback
//...
//your javascript here... below an example of using jquery on some asp.net control.
$('#<%= select.ClientID %>').foo('bar');
}
</script>
http://www.asp.net/ajax/documentation/live/overview/AJAXClientEvents.aspx has some more details about this about 1/3 of the way down the page.
If you still need the answer, there's an analog of ClientScript.RegisterStartupScript for UpdatePanel's partial postback. Try ScriptManager.RegisterStartupScript instead.

Server side JavaScript action

I coded a chat script using AJAX.NET. For every button click I am using the following sample of code in which I am using OnClientClick function to scroll down on every button click i.e. update.
<asp:Button ID="btn_msg" runat="server" Text="Submit" OnClick="btn_msg_Click" OnClientClick="scrolldown('div1')" />
This results fine on the page I am working but in the receiver side scroll bar is not getting down on update. I guess changing the option OnClientClick to some server action will help. I tried adding OnClick="btn_msg_Click; scrolldown('div1');" but this is not working. Is there any alternate way to fulfill my action.
At first glance, I believe Anton is correct. The reason you are seeing this behavior is the order in which everythings runs. The client script runs first. Then the server script. The server script causes a postback( or even via an update panel ), causing it to render the html again, losing the scroll bar position.
Anton's code causes the scrolldown function to run once the ajax postback is complete.
A side note:
If I were doing this, I'd remove the AJAX.NET completely and switch to jquery. You have a lot more control over this kind of stuff.
You need to hook on the endCallback event to scrolldown.
The moment you try to scroll down content is not yet delivered.
Try it this way:
<body onload=”load()”>
<script>
function EndRequestHandler()
{
scrolldown('div1');
}
function load()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
</script>

Categories