Javascript code not being called in asp.net code behind - javascript

I have a block of code (posted below) where if the first IF clause is satisfied, the app does not call the javascript('MyPortfolioItemExists()') function. Instead, it exits the function and goes on to process other code lines.
If drPortfolio.HasRows Then
Dim p As Page = CType(System.Web.HttpContext.Current.Handler, Page)
p.ClientScript.RegisterStartupScript(Me.GetType(), "Script", "javascript:'MyPortfolioItemExists()';", True)
Return ""
Exit Function
ElseIf drFav.HasRows = False And drPortfolio.HasRows = False Then
Utils.ExecNonQuery("insert into UserPortfolio values ('" & PortfoName & "','" & PortfoPage & "','" & Username & "')")
Return GeneratePortfolioContent()
End If
How can I force the javascript function to be executed?

p.ClientScript.RegisterStartupScript just registers the script to be executed on the client. See the documentation for more information on this function.
You can't execute Javascript on the server (unless, of course, you are writing the server-side in Javascript which you are not). Figuring out the difference between server side code and client side code is something many beginners have gotten hung up on and WebForms blurs the line even more.

Related

Pass string variable in C# to javascript function for use in alert box

so what I'm trying to do is pass a simple string variable that contains my error message in C# into my javascript function when I call the function. My function call works fine, but it keeps outputting the wrong thing. This might be important too, I'm calling the Response.Write pieces within my Global.asax.cs file and my javascript file is within my Scripts folder in my MVC project. Based on the research I've found, this is what I currently have after help from the comments:
function KickOutUnwantedUsers(aMesssage) {
console.log("Inside KickOutUnwantedUsers"); //for debugging
console.log(aMesssage); //for debugging
alert(aMessage);
window.open('', '_self').close();
}
It just continues to output this
<%=errorMessage%>
I'm not sure how to fix it, as everything I've found says to pass the variable that way, but I'm wondering if I need to pass it as an actual parameter into the function, and if so, how to do that.
UPDATE: Here is the C# code:
else
{
string user = s.Remove(0, 4);
string errorMessage = "THE FOLLOWING ERRORS MIGHT HAVE OCCURRED: " + user +
" has either been disabled or the account does not exist." +
" PLEASE CONTACT YOUR ADMINISTRATOR. ";
Response.Write("<script type=\"text/javascript\" src=\"Scripts/HelpfulFunctions.js\">");
Response.Write("</script>");
Response.Write("<script type=\"text/javascript\">");
Response.Write("KickOutUnwantedUsers('" + errorMessage + "');");
Response.Write("</script>");
}
SOLVED
#Igor was very helpful in the comments, and I did things as he suggested, which for some reason would not work at first, but then the following day I deletedmy JavaScript file, remade it under the same name and retyped out the javascript code and it worked. Coding is strange sometimes. I must've had a typo or something.
This is what the (badly documented) HttpUtility.JavaScriptStringEncode is for:
// the second argument "true" causes quotation marks to be inserted as well
var message = <%= HttpUtility.JavaScriptStringEncode(errorMessage, true) %>;
First. Such line as
var message = '<%=errorMessage%>';
only makes sense in ASP.NET markup file. In js file it is meaningless, since javascript files are not processed by ASP.NET server-side.
Second. Since you are passing message string as parameter, you need function signature to reflect this:
function KickOutUnwantedUsers(aMessage) {
alert(aMessage);
window.open('', '_self').close();
}
and - note the quotes around the parameter value:
Response.Write("KickOutUnwantedUsers('" + errorMessage + "');");

Javascript Value of Variable not updating in Servlet

I have simplified my Code to breakdown the Problem and to have a simple Example with a Timestamp for whats actually going wrong.
So please not be suprised why i do a AJAX call, this is for the real functionality of the Servlet.
Its a Servlet and the follwing code is part of a JSP page, im Working on JAVA 1.7 and a Tomcat 7. I run it in Firefox and Chrome.
My goal is to retrieve a value from a Java method and write it on the servlet page into the DIV "ContentCharts".
The Problem is that Javascript does not update the vaule of "zeit" and always writes the same Timestamp into the DIV-Container and on the Console
$(document).ready(function()
{
function ausgabe()
{
<%
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
String JZeit = df.format(now.getTime());
System.out.println("FKT ausgabe zeit:"+ JZeit);
%>
var zeit='<%=JZeit %>';
console.info('Zeit:', zeit);
document.getElementById('ContentCharts').innerHTML = zeit;
}
$("#subtab2").click(function()
{
$.ajax
(
{
url:'overview',
data:{dbname:this.className},
type:'get',
cache:false,
success:function(){ausgabe();},
error:function(){alert('error');}
}
);
}
}
To test this I write the value of the JAVA varible "Jzeit" into the Serverlogs and get this (Click to see the Picture) results when I click the buttons three times. As you can see in the Picture here I get the right Timestamps.
Now I have also post the Value of the JS varialbe "zeit" into the Firebug Console. And now i get the Wrong time Stamps (Click to see the Picture)
The Content in the DIV is refreshing but here is the same Problem like in the Console, its always the same Timestamp.
These are my thoughts and Questions:
Why has the JS variable the wrong value when its right in JAVA?
Is there any option to say JS that it has to update the variable?
Could it be that JS saves the answers of the JAVA code and does not run it anymore, but runs the upper JAVA Code Snippet because there is no direct connection betwen JS and JAVA, like a value allocation?
How can i fix my Problem?
If you need more Informations to help me please ask for it.
You're a bit confused about the ajax pattern.
Note that anything you write in <%= jsp tags %> will be rendered on the server, then sent to the client where it will never change. Therefore your ausgabe function will always return the same result when it is called. Subsequent calls to the function will not make repeated server requests, which is the behavior you're observing.
To fix this, the success function in your ajax call should take an argument which will be instantiated with the response from the server. The java code you've written in the jsp tags in the ausgabe function should be moved to the server and any variables you need should be returned from the overview endpoint. Then, the ausgabe function should be refactored to take an argument containing the server-calculated values, and update your page as desired.
Here is some reading on ajax requests:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://api.jquery.com/jquery.ajax/

Set ruby instance variable inside javascript function

I am trying to set a ruby instance variable's value to the latitude and longitude values.
How would you set the value of an instance variable inside a javascript function?
Something like this?
<script>
if (geoPosition.init()){ geoPosition.getCurrentPosition(geoSuccess, geoError); }
function geoSuccess(p) {
<% #lat_lng = p.coords.latidude + "," + p.coords.longitude %>
}
function geoError(){ alert("No Location: Won't be able to use Maps functionality"); }
</script>
Something is telling me I need json.
You are not understanding where and when code runs.
Ruby (on Rails, or otherwise) runs on the server. It creates the HTML+JS+whatever that gets sent over the Internet to the client.
The client (web browser) receives this code and, among other things, executes JavaScript code.
You cannot, therefore, have your Ruby variables be set as the result of running JavaScript code…without contacting the web server again.
You need to use AJAX (or some other, lesser technology) to send a request back to the web server when that function is called.
For example (using jQuery's jQuery.post):
function geoSuccess(p){
$.post('/newcoords',{lat:p.coords.latitude, long:p.coords.longitude});
}
and in some controller somewhere:
def newcoords
#lat_lng = [params[:lat],params[:long]].join(",")
end

javascript form checking and encrypted passwords

I have a simple form where users can change their passwords, and I am using an onsubmit event to check the form which generally works fine, except when I try to stop them using a password already in use.
The passwords are stored in a database and are encrypted. What I need to do is compare the encrypted password with the new password, which is not yet encrypted. The encryption I am using is:
<%
Function encrypt(x1, x2)
s = ""
t = 0
For i = 1 to len(x1)
t = t + asc(mid(x1,i,1))
Next
For i = 1 to len(x2)
y = (t + asc(mid(x2,i,1)) * asc(mid(x2,((i+1) mod len(x2)+1),1))) mod 255
s = s & chr(y)
Next
For i = (len(x2) + 1) to 10
If t>598.8 Then t = 598.8
y = t^3*i mod 255
s = s & chr(y)
Next
encrypt = s
End Function
%>
and I run encrypt(Username,Password) which gives me a output like ¬{±ÝÆÝl
The onsubmit code I am using is
function checkData (){
if (document.signup.password1.value != document.signup.password2.value) {
alert("Your passwords do not match.")
document.signup.password1.focus()
return false
}
if (document.signup.password1.value == "") {
alert("Please enter a password.")
document.signup.password1.focus()
return false
}
}
This all works fine and I am just stuck on the last bit which is the old password check.
I have tried various things like
if (encrypt(document.signup.password1.value,emailaddress) == "value from database"){
alert("The password chosen is already in use.")
document.signup.password1.focus()
return false
}
My main question is: can I call the ASP function encrypt into my javascript checkData? As I am beginning to think this is where the problem is, I am wondering if I am wasting my time and feel that there is no way of doing this. I know I can submit the form to the next page and do the check there but I really wanted to do it this way if I can.
You can not directly invoke ASP (or any other server side language's) functions from JavaScript. That being said, there is a widely used technology called AJAX, which allows you to execute asynchronous JavaScript requests to your server side application. They're called asynchronous, because you do not submit/reload the entire page, but you execute a piece of JavaScript which invokes a server side functionality and returns the result, thus letting you update your page without having to reload it.
In your case, you'd want to implement an AJAX request which asks your if a certain password entered by a user is already in use, and the server will simply return a boolean, which you'd evaluate on the JavaScript side and update your page accordingly.
I'm very certain that there are tons of tutorials and explanations on how to use AJAX requests with ASP (which I am unfamiliar with), and providing such an explanation would certainly be out of what can be provided here. Please consult Google :)

how to assign a javascript variable to a jsp string variable?

i m doing a database project using mysql as the database and jsp for my frontend part along with javascript and ajax for interaction.
Now the problem is i need to assign a java script variable which is having a string to a jsp variable.
I did this using the following statement?
<% String str="document.write(s)"; %>
where "s" is already defined as
<script type="text/javascript">
var s="hello world";
<script>
but i m getting error in the assignment statement(which is shown in bold above) as incorrect syntax?
the error i m getting is-
check the manual that corresponds to your MySQL server version for the right syntax to use near '<script>document.write(s)</script>'
what is the error in this stmt or is there any other method in doing this assignment?
Can anyone help in doing this?
You cannot do this. The JSP statement is executed server-side, before the execution of the Javascript statement, that is executed client-side after the browser received the http response.
It is not clear your goal, but if you only need to display in the page the value of a javascript variable, you can use:
trivial javascript:
document.write(s);
targeting existing element:
document.getElementById('myElementId').innerHTML = s;
using jQuery:
$('#myElementId').html(s);
If i understand correctly you are trying to build and execute a sql query based on user input that is handled by javascript. As ADC said this can not be done since jsp is executed server side therefore before browser executes javascript. What you can do is create the sql query and pass this as a parameter a different jsp/servlet (or the same if you can handle this case) which will execute the query
In the first page where sql statement is constructed in variable s you should put something like this
<script>
var s = "hello world";
function createLink(){
document.getElementById('mylink').href= 'page2.jsp?statement='+s;
}
window.onload=createLink;
</script>
<a id="mylink" href=""/>Click to exexute query</a>
which create a link to you second page (page2.jsp) passing the statement as parameter.
Now in page2.jsp you should retreive the parameter value like
<% String statement = request.getParameter("statement") %>
and then execute your query.
Even better you should use a servlet instead of a jsp page to perform the query. You could read a tutorial for jsp/sevlets to see how this can be done
eg. http://www.laliluna.de/articles/posts/first-java-servlets-jsp-tutorial.html

Categories