__dopostback is not working in javascript function - javascript

am calling __dopostback function in javascript while closing event of browser but its not working in Chrome.
the same function is working in IE
can any one give me the solution.
<script type="text/javascript" language="javascript">
function doUnload()
{
var btnlogout = document.getElementById("ctl00_lbtn_Logout"); alert(btnlogout);
__doPostBack(btnlogout, '');
}
</script>

When doing a __doPostBack, you need to pass the control's UniqueID via javascript. ClientID will not work.

I think you should be passing the btnlogout id as string (not sure if you have to remove the ctl00 thing since it's a child control) as the function expects text and it is probably resolved during the request on the server..
Take a look at this article:
http://wiki.asp.net/page.aspx/1082/dopostback-function/

Just do:
btnlogout.click();
since you already have a reference to the button and, by the way, don't get the element the way you are doing it; do this instead:
var btnlogout = document.getElementById("<%=btn_Logout.ClientID%>");

dopostback(clientID, args)'s first parameter must be a control's clientid, it is a string , not object (of course string is object ) ..
in your case , i assume that is 'ctl00_lbtn_Logout', pass the right params like :
__doPostBack('<%= downloadUp.ClientID %>', current_index);
if your control is server side control, change 'downloadUp' to your control's id , else you just need pass the id

Please try to getElementById this way
var btnlogout = document.getElementById('<%= lbtn_Logout.ClientID %>');
alert(btnlogout)
and test it again , it will work..

Related

Razor Syntax in External Javascript

So as you might know, Razor Syntax in ASP.NET MVC does not work in external JavaScript files.
My current solution is to put the Razor Syntax in a a global variable and set the value of that variable from the mvc view that is making use of that .js file.
JavaScript file:
function myFunc() {
alert(myValue);
}
MVC View file:
<script language="text/javascript">
myValue = #myValueFromModel;
</script>
I want to know how I can pass myValue directly as a parameter to the function ? I prefer to have explicit calling with param than relying on globals, however I'm not so keen on javascript.
How would I implement this with javascript parameters? Thanks!
Just have your function accept an argument and use that in the alert (or wherever).
external.js
function myFunc(value) {
alert(value);
}
someview.cshtml
<script>
myFunc(#myValueFromModel);
</script>
One thing to keep in mind though, is that if myValueFromModel is a string then it is going to come through as myFunc(hello) so you need to wrap that in quotes so it becomes myFunc('hello') like this
myFunc('#(myValueFromModel)');
Note the extra () used with razor. This helps the engine distinguish where the break between the razor code is so nothing odd happens. It can be useful when there are nested ( or " around.
edit
If this is going to be done multiple times, then some changes may need to take place in the JavaScript end of things. Mainly that the shown example doesn't properly depict the scenario. It will need to be modified. You may want to use a simple structure like this.
jsFiddle Demo
external.js
var myFunc= new function(){
var func = this,
myFunc = function(){
alert(func.value);
};
myFunc.set = function(value){
func.value = value;
}
return myFunc;
};
someview.cshtml
<script>
myFunc.set('#(myValueFromModel)');
myFunc();//can be called repeatedly now
</script>
I often find that JavaScript in the browser is typically conceptually tied to a specific element. If that's the case for you, you may want to associate the value with that element in your Razor code, and then use JavaScript to extract that value and use it in some way.
For example:
<div class="my-class" data-func-arg="#myValueFromModel"></div>
Static JavaScript:
$(function() {
$('.my-class').click(function() {
var arg = $(this).data('func-arg');
myFunc(arg);
});
});
Do you want to execute your function immediately? Or want to call the funcion with the parameter?
You could add a wrapper function with no parameter and inside call your function with the global var as a parameter. And when you need to call myFunc() you call it trough myFuncWrapper();
function myFuncWrapper(){
myFunc(myValue);
}
function myFunc(myParam){
//function code here;
}

XPages csjs pass a variable into a function?

On a button click, I'm calling a function in client side JavaScript.
doIt("TEST");
"TEST" is just the ID of label on my XPage.
In the function, I want to use the variable I passed as an ID. Something like:
function doIt(item){
alert(dojo.query("[id$=':item']").innerHTML);
}
OR
function doIt(item){
val = XSP.getElementById("#{id:item}").innerHTML;
alert(val);
}
I have also tried using this, which gives undefined:
val = dojo.query("[id$=':" + item + "']").innerHTML;
alert(val);
If I hard code the ID name like so, then I get the correct innerHTML of the element with the ID "TEST":
val = XSP.getElementById("#{id:TEST}").innerHTML;
alert(val);
Where is my syntax wrong when trying to write this very simple line of code used the passed variable?
The easiest way is to call your function with the complete id:
doIt("#{id:Test}")
and to use it in your function
function doIt(item){
alert(dojo.byId(item).innerHTML);
}
In the "onclick" client-event in the button, (inside XPage or CC), the client Ids can be computed, so you should put there something like this:
doIt("#{id:Test}"); // << "#{id:Test}" is computed in the server-side and the final client ID is sent to the browser
Then, in your cjs library (cjs libraries are not "evaluated" before sending to the client, so here you cannot use "#{id:Test}" expressions) you should have something like:
function doIt(idElement) {
var domElem = dojo.byId(idElement); // << here you get the element
}

Can I Pass a JS Object or Reference to a JS Object to a Function in the HTML Markup?

Pretty noobish question, and I'm probably thinking about this wrong, but...
Is there a way to pass a javascript object (or a reference to it) to a javascript function within the HTML markup?
For example:
<script type="text/javascript">
var myObject = new Object();
$('body').append('<div onclick=testThis(' + myObject + ')></div>');
function testThis(object)
{
console.log(object);
}
</script>
The markup ends up looking something like this when I inspect it:
<div onclick="testThis([object Object])">
Additional context:
The real use case is a search page in which I am querying SOLR via AJAX and get a result back as JS objects. When the user clicks on the HTML markup representing one of these search results, I want to be able to pass the object(or a reference to it) to a separate JS function for processing.
Am I thinking about this the wrong way?
No, you can't embed a reference to an object into markup.
Instead you probably would like to setup your click event listening in Javascript/jQuery:
var object = new Object();
$('<div/>').appendTo('body').click(function() {
testThis(object);
});
function testThis(value) {
console.log(value);
}

Passing event args from javascript to code-behind while using ClientScript.GetPostBackEventReference

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));

Unable to re-define a function in my javascript object

I have an object defined using literal notation as follows (example code used). This is in an external script file.
if (RF == null) var RF = {};
RF.Example= {
onDoSomething: function () { alert('Original Definition');} ,
method1 : function(){ RF.Example.onDoSomething(); }
}
In my .aspx page I have the following ..
$(document).ready(function () {
RF.Example.onDoSomething = function(){ alert('New Definition'); };
RF.Example.method1();
});
When the page loads the document.ready is called but the alert('Original Definition'); is only ever shown. Can someone point me in the right direction. I basically want to redefine the onDoSomething function. Thanks, Ben.
Edit
Thanks for the comments, I can see that is working. Would it matter that method1 is actually calling another method that takes the onDoSomething() function as a callback parameter? e.g.
method1 : function(){
RF.Example2.callbackFunction(function() {RF.Example.onDoSomething();});
}
Your code as quoted should work (and does: http://jsbin.com/uguva4), so something other than what's in your question is causing this behavior. For instance, if you're using any kind of JavaScript compiler (like Closure) or minifier or something, the names may be being changed, which case you're adding a new onDoSomething when the old one has been renamed. Alternately, perhaps the alert is being triggered by something else, not what you think is triggering it. Or something else may have grabbed a reference to the old onDoSomething (elsewhere in the external script, perhaps) and be using it directly, like this: http://jsbin.com/uguva4/2.
Thanks for the response .. in the end the answer was unrelated to the code posted. Cheers for verifying I wasn't going bonkers.

Categories