Javascript not sending id in query string - javascript

I have a JavaScript function to passing a query string and when I get to the page that its being redirected to, but when I step through the code the id is not being passed.
the JavaScript is
function OpenRadWindow(sender, eventArgs) {
window.radopen("BankStatements_Update.aspx?id=" + eventArgs.getDataKeyValue("id"), "RadWindow1");
}
the code for the page to receive the query string is
string a = Request.QueryString["id"].ToString();
however if I use the selected change event then I can get the id using this in the code behind..
string a = (RadGrid2.SelectedItems[0] as GridDataItem).GetDataKeyValue("id").ToString();
this works fine, however I have been looking around for awhile now and can't find a way to open radwindow from the code behind.
I have tried using this script to call the javascript function to open the radwindow..
string script = "<script language='javascript' type='text/javascript'>Sys.Application.add_load(OpenRadWindow);</script>";
ClientScript.RegisterStartupScript(this.GetType(), "showWindow", script);
but it wouldn't fire.
So I am left to using the original script that I showed and I have no idea why I'm not getting the id.

window.radopen is framework method ? maybe is window.open?
ref http://www.w3schools.com/jsref/met_win_open.asp
or you can do that in your javascript function
function OpenRadWindow(sender, eventArgs) { console.log(eventArgs.getDataKeyValue("id"));}
And use browser console check your value

Related

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/

Show a Client Alert After the codebehind has been processed. ASP.NET

I have this code behind in my ASP.NET 4 Web Forms app:
Protected Sub BTNSave_Click(sender As Object, e As EventArgs) Handles BTNSave.Click
If saveOnDB() Then
showOkAlert()
Else
showErrorAlert()
End If
End Sub
I need to show a client alert when something done in the code behind has gone OK or an error has happened. Any idea?
I haved tied Response.Write("<script>alert('Successfully added');</script>") but this never works and even creates an error in the browser's console: "Uncaught Sys.WebForms.PageRequestManagerParserErrorException: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed."
Also I don't use OnClientClick because it triggers the javascript before the codebehind.
I do something similar. I've hacked some working code to simplify it as an example for your particular use:
private void RegisterJavascriptForUpdatePanelExample(UpdatePanel myUpdatePanel, string myMessage)
{
const string JAVASCRIPT_TEMPLATE = "javascript: jQuery(function($) {{ alert({0}); }});";
const string SCRIPT_KEY_TEMPLATE = "KeyForRegisterJavascriptForModalPopup_{0}";
string scriptkey, scriptstr;
scriptkey = string.Format(SCRIPT_KEY_TEMPLATE, myUpdatePanel.ClientID);
scriptstr = string.Format(JAVASCRIPT_TEMPLATE, myMessage);
ToolkitScriptManager.RegisterClientScriptBlock(myUpdatePanel, myUpdatePanel.GetType(), scriptkey, scriptstr, true);
}
In this example, a simple JavaScript alert() is called to display your message, like this:
RegisterJavascriptForUpdatePanelExample("A-OK!");
Of particular interest is the ToolkitScriptManager.RegisterClientScriptBlock function. There are several variations of this, depending if the JavaScript code should be embedded and executed within an UpdatePanel, or when the page loads, or other situations. It can be kind of confusing to decide which function is needed, but it's just what you need.

Pass in javascript param in URL

I'm trying to back end this and maybe get lucky modifying the url, what happens is there is javascript code that loads specific data and I want to be able to pass in the script via the URL. Is this possible and how would i do it?
For example here is the javascript: javascript:ChangeEvsVol('1035','3')
here is the urL:https:///app/template/simple%2CDownloadQuotasScreen.vm
Is there a way to manipulate the URL to use that param? I throw in into Firebug command console and it grabs exactly what I need.
document.location ="mysite.php?var1=" + JSvar1 +"&var2=" + JSvar2

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

Servlet calling from window.showModalDialog(...)

I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks

Categories