I want to set the value of a javascript variable into the jsp request/session via request.getSession().setAttribute(obj, obj), so that I can use it later.
I wrote below piece of code,
function setVal(cache){
var vo = cache;
String voStr = vo;
<% request.getSession().setAttribute("single_"%>+voStr+<%, "true"); %>
}
Here, I called the 'setVal' func, by the onclick event of a button and there's no error showing in the syntax, so I hope the syntax is correct.
But while I'm running the jsp, it's causing JasperException/ ServletException in the console.
javax.servlet.ServletException: Unable to compile class for JSP:
An error occurred at line: 46 in the jsp file: /home.jsp
The method setAttribute(String, Object) in the type HttpSession is not applicable for the arguments (String)
Can anyone please suggest, how can I set value in the request.getSession().setAttribute , via a javascript function.
Related
I have a dropdownlist on a View as:
<p>
#Html.DropDownList("Status", new List<SelectListItem>
{
new SelectListItem{ Text = "Show Active", Value = "0" },
new SelectListItem{ Text = "Show Deleted", Value = "1" }},
new
{
onchange = #"
var form = document.forms[0];
form.action='deletedDistricts';
form.submit();"
})
and I am referring it to controller action as:
[HttpPost]
[ActionName("deletedDistricts")]
public ActionResult deletedDistricts()
{
var d = hc.deletedDistricts.ToList();
return View(d);
}
but JavaScript is giving a runtime error as:
0x800a138f - JavaScript runtime error: Unable to set property 'action' of undefined or null reference
I am not very good at JavaScript. Any idea why this code is throwing Null reference?
Well I can't see that you would have a form associated with a dropdown, make sure that it's wrapped with:
#using(Html.BeginForm("deletedDistricts", controllerName, FormMethod.Post)) {
// drowpdown here
}
And remove form.action='deletedDistricts';
conrollerName should be name of your controller as a string.
Let's read the error you are getting once again:
0x800a138f - JavaScript runtime error: Unable to set property 'action'
of undefined or null reference
OK, now let's read your code once again to see where you are attempting to set an action property. Looks like that's happening right over here:
form.action='deletedDistricts';
Alright, so it seems like the form instance is undefined at this stage. So the obvious next step you would like to look at is where is this form instance coming from. And you wouldn't be surprised to find this line of code of yours:
var form = document.forms[0];
Cool, you seem to be attempting to retrieve the first <form> element in your DOM. But do you have such element? Did you ever use the Html.BeginForm helper to render an HTML form? Answering those simple questions would definitely put you on the right track. Don't hesitate to inspect the markup you are generating in the browser. I am sure this would help you figure out the missing bits.
I am trying to figure out the correct javascript syntax for a DevExpress datagrid callback to pass data back to the client.
In the .aspx I installed an onclick event in the DataGrid row with a CustomCallback event using the js call: dg.PerformCallback(key); and in the aspx.cs file this function is correctly reached, however I cannot pass data back to the client:
protected void dg_CustomCallback(
object sender,
DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
{
string key = e.Parameters; // works
e.Results = "something"; // .Results does not exist
return;
}
Then I switched from a CustomCallback to a DataCallback because the DevExpress.Web.ASPxGridView.ASPxGridViewCustomDataCallbackEventArgs does have a .Results property. However, I cannot figure out the corresponding javascript call. I tried in vain: dg.PerformCallback(key); , dg.PerformDataCallback(key); and dg.SendCallback(key);
Also I am wondering, when the above problem is fixed, which js function I need to program to receive the return data from the server after the callback.
What you are trying to achieve can be done using the JSProperties on callback and the OnEndCallback client side event of the ASPxGridview. This aspx tag can be placed exactly after the </Columns> closing tag of the ASPxGridview.
<ClientSideEvents EndCallback="function(s,e)
{
var errText = s.cpError;
if (errText != "")
{
alert(errText);
}
}" />
On the server side you set the JSProperties like this
gridOfApp.JSProperties["cpError"] = "The error was major!";
Important. Bear in mind that your JSProperties MUST ALWAYS start with the cp prefix.
How do I conditionally invoke JavaScript from a bean in JSF 2?
I have a class that uses PrimeFaces which uploads user files to a particular folder, but if the user attempts to upload a file with the same name as one that is already present, I want JavaScript in this case to open up a box on the screen asking the user if he wants to overwrite the old file, or cancel the operation. If no file with that name is present, then JavaScript is not called.
I know how to test that a folder has a particular file in it, it is just that I need to know how to invoke JavaScript conditionally.
I would most appreciate any advice on this.
I have looked at variopus resources online, but still cannot get the application to work correctly. basically, this is what I have done, in an included xhtml page I have the following code for the file upload:
<p:fileUpload id="fileUpload" fileUploadListener="#{filters.upload}"
allowTypes="#{filters.uploadTypes}" invalidFileMessage="#{filters.uploadBadType}"
sizeLimit="#{filters.uploadSize}" invalidSizeMessag="#{filters.uploadBadSize}"
update="fileUpload fileTable uploadMessage" description="Select Text File"
disabled="#{filters.disableFileUploadButton}"/>
<!--- Then further in the same file is this: -->
<p:remoteCommand name="remoteCommandOverwrite" actionListender="#{filters.execOverwrite}"/>
The parent xhtml page that includes the above I have the foolowing JavaScript:
<script type="text/javascript">
function popupConfirm() {
var overwrite = confirm('Warning: This will overwrite the existing file - Do you confirm this?');
if (overwrite) remoteCommandOverwrite([{name: overwrite, value: true}]);
}
</script>
In my bean I have the following code in three methods:
public void upload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
overwrite = false;
// Do what you want with the file
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
// Initialization etc.
File file = new File(uploadFull + fileName);
if (file.exists()) {
RequestContext.getCurrentInstance().execute("popupConfirm()");
// Then test to see if overwrite is true or false, and act accordingly
}
// Then I am supposed to get the value of overwrite here:
public void execOverwrite() {
System.out.println("### execOverwrite() ###");
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> map = context.getExternalContext().getRequestParameterMap();
String soverwrite = (String) map.get("overwrite");
if (soverwrite.equals("true")) {
overwrite = true;
System.out.println("overwrite: true");
}
}
What I am trying to do is first to invoke conditionally the JavaScript function popupConfirm(). On clicking the "Upload" button that is invoked if the codition is true, which is what I want. This is then supposed to call
That works and brings up the confirm() box, but the is never called, so the method execOverwrite() in my bean is also never called, and I cannot pick up the return value and pass it to the code inside the method copyFile(). What is going wrong?
I put this problem on the back burner for about a week, and have just got back to it. I got it to work, and can pass a value back to the bean, but somehow I need to resume execution from the place where JavaScript is called.
To sumarize, my JavaScript contains the following code:
<script type="text/javascript">
function popupConfirm() {
var overwrite = confirm('Warning: This will overwrite the existing file - Do you confirm this?');
if (overwrite) remoteCommandOverwrite([{name: 'overwrite', value: 'true'}]);
}
</script>
And in the xhtml code I have:
<p:fileUpload id="fileUpload" fileUploadListener="#{filters.upload}" ...../>
<!-- Other code -->
<p:remoteCommand name="remoteCommandOverwrite" actionListener="#{filters.execOverwrite}"/>
Then on clicking the file upload button after clicking the choose file button, the code in the JavaScript, as listed above, is executed:
RequestContext.getCurrentInstance().execute("popupConfirm()");
Then on clicking "OK" in the dialog box, this method in the same bean is called:
public void execOverwrite() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> map = context.getExternalContext().getRequestParameterMap();
String soverwrite = map.get("overwrite");
if (soverwrite.equals("true")) {
overwrite = true; }
}
}
where the flag "overwrite" will eventually be tested to see if it is true.
Using various print statements I check that this works. However, the code does not resume executing after encountering the statement: RequestContext.getCurrentInstance().execute("popupConfirm()"); regardless of whether I enter "OK" or "Cancel" in the dialog, which is what i want it to do. It looks as if a callback of some type is required, and would most appreciate some ideas.
According to your tag, you are using PrimeFaces, so there is an easy way to invoke a javascript function from a server side event managed bean method when the browser has completed processing the server response. PrimeFaces gives you a utility class called RequestContext.
public void doActionListenerMethod() {
if (!isValid()) {
RequestContext.getCurrentInstance().execute("MyJSObject.doClientSideStuff()");
}
}
The following will execute the string argument as a Javascript when JSF has finished rendering on the client.
So, I've created a function to do some error checking on an XML file that I recieve from an AJAX call. Part of the validation is that the function then builds out an object for easy access while I process that data into a form. In FF, works like a charm. IE dies with the error:
Object doesn't support this property or method
Here is the function (minus the un-important bits):
function checkReceiveXMLTagString( doc, messageObject, tag ) {
var tag_nodes = doc.getElementsByTagName( tag );
...do some error checking...
messageObject[tag] = tag_str; <-- error occurs on this line
return true;
}
Here is an example of how the function is call:
if ( checkReceiveXMLTagString( messageObject.Name[0], messageObject.Name[0], "First" ) ) {
...process messageObject.Name[0].First...
}
Like I said, FF has no issues. Safari loads the pages as well. IE has issues.
Thanks!
Looks like something is making messageObject be null or undefined
If the error is on this line:
messageObject[tag] = tag_str;
Then, the only two ways I know of that that can cause an error are:
messageObject is not an object that you can set properties on (null or undefined are the most likely ways that would happen)
tag is null or undefined
Since I see that your code calls this function hundreds of times so you can't effectively just break on it, I'd suggest you put in some defensive coding to check for those conditions and output something to the debug console to identify what the state is when the problem occurs. You can even trigger a conditional breakpoint with code like this:
if (!messageObject || !tag) {
debugger;
}
In the toughest cases, you can put an exception handler around it and break when the exception is thrown:
try {
messageObject[tag] = tag_str;
} catch(e) {
debugger;
}
Both of these will allow you to capture the condition in the debugger and examine all your parameters at the time of the error.
I'm trying to trigger a postback from java-script and also pass event args. I'm able to trigger the postback **but not able to pass event args.
The below function does not work. It does not like the args parameter in ClientScript.GetPostBackEventReference.
<script type="text/javascript">
function TriggerServerSideClick(args) {
//btnDummy is a asp.net server-side button control
<%=ClientScript.GetPostBackEventReference(btnDummy, args , true)%>
//tried this -> <%= 'ClientScript.GetPostBackEventReference
// (btnDummy,' + args + ', true)' %> ,
// but i guess i am definitely missing something.
}
</script>
What am I missing here ?
I know that the following works
__doPostBack('btnDummy', args);
but want to stay away from __doPostBack as that could change eventually and try the ClientScript.GetPostBackEventReference instead.
Thanks for your time.
#Brian: Thanks a lot for following up. I tried your placeholder approach but I am getting a javascript error. (Message: Expected ';')
Here is the viewsource snippet:
var postbackUrl = '__doPostBack('ctl00$MainContent$btnDummy','{0}')';
function TriggerServerSideClick(args) {
var url = String.format(postbackUrl, args);
eval(url);
}
Try this:
var postbackUrl = '<%=ClientScript.GetPostBackEventReference(btnDummy, "{0}", true)%>';
function TriggerServerSideClick(args) {
var url = String.format(postbackUrl, args);
eval(url);
}
Put a placeholder where the argument should be, then use a client-side method to replace the placeholder (client-side String.format method) and use that to postback.
HTH.
The answer from Brian Mains sent me in the right direction when I was working on this issue just now. The only difference being, that I didn't use the client-side string.Format - I used the mainstream JavaScript string.replace:
//js
args = someComplicatedDynamicStuff();
myPostback = <%= Page.ClientScript.GetPostBackEventReference(this, "args")
.Replace("'", "\\'") %>; // server-side replace to
// inject string delimiters
eval(myPostback.replace('args',args));