Run javascript on button press ASP.NET - javascript

I would like to call javascript function in case something in my code behind would happen.
If it is like the code below it works fine after postback alert windows shows and says it correctly. But in case I remove the comment from else block none of those two scripts in else block will happen?
Is there any limit on how many of these action could I make from codebehind?
if (condition) {
if (condition2) {
var message = "It happened !";
Page.ClientScript.RegisterStartupScript(this.GetType(), "yep1", "alert('" + message + "')", true);
}
} else {
var msg = "It does not work like that";
Page.ClientScript.RegisterStartupScript(this.GetType(), "nope1", "alert('" + msg + "!')", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(), "nope2", "alert('" + msg + "')", true);
}

This way it will work. As the name of the function says, it register the startup script so you are changing it instead of inserting 2. In this way it will do both ^^
if (condition)
{
if (condition2)
{
var message = "It happened !";
Page.ClientScript.RegisterStartupScript(this.GetType(), "yep1", "alert('"+message+"');", true);
}
}
else
{
var msg = "It does not work like that";
Page.ClientScript.RegisterStartupScript(this.GetType(), "nope1", "alert('"+msg+"!'); alert('" + msg + "');", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(), "nope1", "alert('"+msg+"!')", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(), "nope2", "alert('" + msg + "')", true);
}

Related

Alert before redirect showing value with message in asp

I am trying to display a string along with the message.But i get an error.
str1 is a value retrieved from a table
the code is
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect", "alert('Welcome'); window.location='" +
Request.ApplicationPath + "#';", true);
but i want to display it as follows
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect", "alert('Welcome '" + tbEmail.Text + "''); window.location='" +
Request.ApplicationPath + "#';", true);
I'm just a beginner,any help is appreciated ,thank you

alert not showing exception variable in asp.net

I want to show exception in alert box in asp.net 4. But it is not showing any alert.
I tried these solutions -
try{// my code}
catch (Exception ex)
{
//Response.Write("<script>alert('" + Server.HtmlEncode(ex.Message) + "')</script>"); // Not Working
//Response.Write("<script>alert('" + ex.Message + "');</script>"); // Not working
// Response.Write("<script>alert('" + Server.HtmlEncode(ex.ToString()) + "')</script>"); // Not working
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "done", "alert('Error Occured.');", true); // Only this is working.
}
Please suggest any solution to this where I am going wrong.
Thanks and regards,
Rizwan Gazi.
Normally Response.Write(); always works. But as you said its not working than
Try this :
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "done", "alert('" + ex.Message.Replace("'", "") + "');", true);
Let me know if it solves your issue.

Ajax request after sometime freeze browser

I have made admin panel where setup notification alerts using ajax. It is working fine, but after few minutes than it starts to freeze the browser. Any idea what I am doing wrong, as it is my first Ajax project.
Following are codes which I am using, I used setInterval in a function which is called by body onload event.
<html>
<body onload="process()">
<-- Some notification divs to be replaced by javascript -->
</body>
<html>
JavaScript
<script>
var xmlHttp = createXmlHttpRequestObject();
function process() {
setInterval('process()', 10000);
if (xmlHttp) {
try {
xmlHttp.open("GET", "response.json", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
} catch (e) {
console.log("Can't connect to server:\n" + e.toString())
};
}
}
function handleRequestStateChange() {
if (xmlHttp.readyState == 4) {
{
if (xmlHttp.status == 200) {
try {
handleServerResponse();
} catch (e) {}
} else {
console.log("There was a problem retrieving the data:\n" + xmlHttp.statusText);
}
}
}
}
function handleServerResponse() {
responseJson = JSON.parse(xmlHttp.responseText);
for (var i = 0; i < responseJson.newbooking.length; i++) {
// html += "<li><a href='admin_user.php?id=" + + "'><div class='desc'>" + responseJson.users[i].first_name + ", " +responseJson.users[i].last_name + " joined</div></a></li>";
bookinghtml += "<li><a href='makeinvoice.php?bookingid=" + responseJson.newbooking[i].booking_id + "'><span class='subject'><span class='from'>" + responseJson.newbooking[i].company_name + " </span><span class='time'> " + responseJson.newbooking[i].user_name + " </span></span>";
bookinghtml += "<span class='message'> from " + responseJson.newbooking[i].start_date + ", " + responseJson.newbooking[i].batches + " " + responseJson.newbooking[i].campaign + "</span></a></li>";
}
myDiv = document.getElementById("bookinginfo");
myDiv.innerHTML = bookinghtml;
}
Every time you make a request, you tell it to make a request every 10 seconds.
So onload, you make a request and start a timer.
10 seconds later you make another request and start another timer.
10 seconds later you make two requests, each of which starts another timer.
10 seconds later you make four requests, each of which starts another timer.
and so on.
It starts freezing, because it eventually is making trying to make requests faster then the computer can handle.
Use setTimeout, not setInterval.
(Also, you should pass a function, not a string: setTimeout(process, 10000));

XMLRequest ResponseText is blank

I've got a JavaScript function that I want to report an alert message to the users if it successfully updates the database, or if it has an error.
In the main X.JSP file I have:
function startRequest(pChange)
{
//alert("startRequest");
createXmlHttpRequest();
//alert("sending message");
//var u1=document.f1.user.value;
//alert("Running startRequest for: " + pChange.id);
//xmlHttp.open("GET","updateEntry.jsp&pID=pChange.id&pStatus=pChange.status&pAddress=pChange.address&pDate=pChange.date&pNotes=pChange.note&pAssigned=pChange.assigned" ,true)
xmlHttp.open("GET","updateEntry.jsp?pID=" + pChange.id + "&pAddress=" +pChange.address + "&pStatus=" + pChange.status +"&pNote=" + pChange.notes +"&pAssigned=" +pChange.assigned ,true)
//alert(xmlHttp.responseText);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
function handleStateChange()
{
//alert("handleStateChange");
var message = xmlHttp.responseText;
alert("Return Code:" + message);
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
}
}
else
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
}
I then run a method in updateEntry.jsp that does a number of things, but of interest is this section:
if(nId.equals("NMI")||nId.equals("MI")||nId.equals("NI")||nId.equals("SA")||nId.equals("S"))
{
org.hibernate.Query query2 = session2.createQuery("update Leads set Status = :nstatus where Id = :nid");
query2.setParameter("nid", nId);
query2.setParameter("nstatus", nstatus);
query2.executeUpdate();
out.println("Update successfully with: " + nstatus);
// Actual contact insertion will happen at this step
session2.flush();
session2.close();
}
else
{
out.println("Status must be: NMI, MI, NI, SA or S");
}
My understanding is that this should only create a single alert, if the function completes successfully. Instead it creates like 9 alerts all of which are blank. What am I doing wrong? I'm seeing both the "Return Code: " message and a blank " " message, (two different sections of code) but both output blank message variables.
If the readystate is not 4, it does not mean it is an error. Ajax has multiple states that inform the clientside about what is happening. Your code says that those connection states are all errors.
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
} <-- your else should most likely be up here
}
else <-- this is incorrect
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
Read the document at MDN - Ajax Getting Started

passing a parameter to a JavaScript function

int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2(" + i + ")", true);
function f2(i) {
if (i == 1) {//CariKartHareketleri
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.location.href = window.opener.location.href; //çağıran sayfayı yeniliyor
}
else if (i == 2) {//islemler
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.__doPostBack('GridRefreshPanel.ClientID', '');
}
else if (i == 3) {//hizmet listesi
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.__doPostBack('GridRefreshPanel.ClientID', '');
}
}
it says i is undefined when I debug the code in f2(i).What am i doing wrong?
EDIT: I learned many things from this problem, but I still do not have an answer.I tried every idea given in the answers but i is still undefined...
EDIT: I still have no solution for undefined reasons :), but the answer I accepted would normally be my solution.
Have you tried debugging the server-side code to see if
int i = Convert.ToInt32(Session["sayfaTuru"]);
is giving you what you want in the first place?
Well seeing as how the above has been checked, I went ahead and created my own test, and it worked just fine. Here's the test I used:
JS:
<script type="text/javascript">
function f2(i, hiddenFieldId, updatePanelId) {
console.log(i + ', "' + hiddenFieldId + '", "' + updatePanelId + '"');
var hiddenField = window.opener.document.getElementById(hiddenFieldId);
switch (i) {
case 1: //CariKartHareketleri
hiddenField.value = "hello world 1";
window.opener.location.href = window.opener.location.href; //çağıran sayfayı yeniliyor
break;
case 2: //islemler
hiddenField.value = "hello world 2";
window.opener.__doPostBack('' + updatePanelId + '', '');
break;
case 3: //hizmet listesi
hiddenField.value = "hello world 3";
window.opener.__doPostBack('' + updatePanelId + '', '');
break;
default:
alert("error");
break;
}
}
</script>
C#:
Session["sayfaTuru"] = 2; // initialize for testing purposes
int i = Convert.ToInt32(Session["sayfaTuru"]);
string script = string.Format("f2({0}, '{1}', '{2}');",
i.ToString(),
this.HiddenField1.ClientID,
this.GridRefreshPanel.UniqueID);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", script, true);
console.log Output:
2, "HiddenField1", "GridRefreshPanel"
ClientScript.RegisterStartupScript takes a script definition, not an invocation.
Since you want to define the function externally, use this method instead:
ClientScript.RegisterClientScriptBlock(this.GetType(), "RefreshOpener", "MyJavaScriptFile.js", true);
To execute the JavaScript function f2 with parameter Session["sayfaTuru"] on button click, use the following (not tested):
In Page_Load, add the JavaScript file which contains the definition for f2:
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(...);
// Do other stuff
}
Then add the actual button click listener which will invoke f2:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="f2(<%=Session['sayfaTuru']%>);" />
I think you may be getting an Exception thrown in your code-behind. You're trying to concatenate strings, but i is an integer. Try this instead:
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2(" + i.ToString() + ")", true);
Though I would actually prefer to use String.Format:
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", String.Format("f2({0})", i), true);

Categories

Resources