do a postback with javascript to a certain Page Method - javascript

What I'm doing now is this:
<div style="display:none;">
<asp:Button runat='server' OnClick='OnDoClick' ID="b1" />
<asp:HiddenField runat='server' ID="SecretValue" />
</div>
function doPostb(value)
{
$('#SecretValue').val(value);
$('#<%=b1.ClientID%>').click();
}
so basically I need to post to a page method and send some value to it
anybody knows a more straightforward way of doing this ?

Straightforward? Wrap your div in a form tag and do:
$("#your_new_form").submit()

If you want to do it without the page re-loading, you could try jQuery's post function.
If you want to do it without the page re-loading, you could try jQuery's submit function, which would behave the same as the click of a submit button, but might be more semantically appropriate.
You might also want to look at asp.net's doPostBack function.

You can use __doPostBack method of asp.net Client-library.
function doPostb(value)
{
$('#SecretValue').val(value);
__doPostBack('<%=b1.UniqueD%>','');
}
I can't get that why you mentioned about PageMethods ??

Related

Button onclick event does not redirect to another page although it calls the functions

The following code does not redirect to the given webpage
<form>
<button onclick='window.location.replace("../magnet/index.php")'>Replace document</button>
</form>
It is so because when you create a button within the form tags, it is created as a submit button by default. So, instead of redirecting the webpage, it submits the data and reloads the current webpage.
The following code will do the required job because now, the type of the button is button and not submit.
<button type="button" onclick='window.location.replace("../magnet/index.php")'>Replace document</button>
Even better, you can place your redirect code into a JavaScript function. Then you can call that function from within your HTML code. Like this
<script type="text/javascript">
<!--
function redirectTo(sUrl) {
window.location = sUrl
}
//-->
</script>
<button onclick="redirectTo('../magnet/index.php')">Get HTML!</button>
Hope this will work for you. Cheers
The answer was to add type="button" like #shivamag00 explained.
But be careful with replace(), it's not possible to use "back" to navigate back to the original document since you are replacing the history state.
An alternative is to use the assign() function, (documentation here)
Suppose you have a base url as
www.website.come
and want to go to
www.website.come/new-page
it's simple
<button type="button" onclick='window.location.assign("new-page")'>Go to new page</button>
It's worked for me, hope it's useful for someone else.

Calling button click from JavaScript asp.net doesn't work

I am trying to invoke a server side method through JavaScript by first displaying a confirm message and then trigger a button click on the page to call the function. However, the .click() method doesn't seem to work. Any ideas?
<script type="text/javascript">
function confirmDelete() {
var button = document.getElementById("hiddenButton");
if (confirm("Are you sure you would like to delete the row")) {
button.click();
}
}
</script>
and the button is defined like follows
<asp:Button ID="hiddenButton" runat="server" onclick="showHiddenMessage" Text="hidden" width="100px" />
Everything that I have found suggest that it should. including here:
http://www.comptechdoc.org/independent/web/cgi/javamanual/javabutton.html
and here:
Call ASP.NET function from JavaScript?
var button = document.getElementById('<% =hiddenButton.ClientID %>');
Id of server side controls is different on client side. modify code as above and try.
Modify confirmDelete() method as below:
function confirmDelete() {
if (confirm("Are you sure you would like to delete the row")) {
__doPostBack(( 'hiddenButton', '' );
}
}
Take a look at the ClientIDMode property of a Button. Setting this to Static will cause the button to render with the ID you entered in to your ASP.NET code. https://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx
<asp:Button ID="hiddenButton" runat="server" ClientIDMode="Static" onclick="showHiddenMessage" Text="hidden" width="100px" />
If you look at the generated HTML, you should see the ID of this button as hiddenButton which should allow your Javascript to work.
By default ClientIDMode value will be Inherit, and will include the NamingContainer within the ID. This means the ID of the rendered HTML will be something like Panel1_hiddenButton and your Javascript won't find it with the current code.
For reference:
Static - The ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains.
Inherit - The control inherits the ClientIDMode setting of its NamingContainer control.
But why don't you use your javascript function with your button? I think it is better:
<script type="text/javascript">
function confirmDelete() {
if (confirm("Are you sure you would like to delete the row?")) {
return true;
}
return false;
}
And your button:
<asp:Button ID="hiddenButton" runat="server" OnClientClick="return confirmDelete();" onclick="showHiddenMessage" Text="hidden" width="100px" />
In this case if user will click OK button, your showHiddenMessage function will occur. Otherwise nothing will be happen.

Unable to make ASP.NET control button fade out with JQuery

I have a simple enough problem: I have an ASP.NET control button and I want to make it fade out and then call some function (such as an alert) using JQuery. Here is what I have so far:
ASP Code for the Button:
<div id="begin">
<span id="startButtonSpan">
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick()"/>
</span>
</div>
JavaScript:
function startButtonClick()
{
$("#startButtonSpan > input").fadeOut(500, callAlert());
}
function callAlert()
{
alert("Made it here...");
}
When I click the button, the alert displays but the page does not even seem to try to perform the fadeOut. When I close the alert, the button is still there, staring at me.
Can anyone see any mistakes or does anyone have any suggestions on how I might be able to achieve the intended goal of fading out my button? Fadeout is really just my way of testing whether I can manipulate ASP controls using jQuery, so more than just the simple fadeOut, this is me trying to learn how to do that.
I tried a slightly more simple jQuery call using the code below, but it does not seem to work either:
ASP Portion:
<div id="begin">
<span id="startButtonSpan">
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick()"/>
</span>
</div>
<div id="jQueryTest" style="display:none;">
Block for testing jQuery.
<h1 id="testMessage">Child element for the ASP div.</h1>
</div>
Javascript Portion:
function startButtonClick()
{
$("#jQueryTest").css("display", "block");
$("#jQueryTest").show();
}
For this example, the text does display, but it immediately disappears again.
Any help or suggestions as to what I might be doing wrong would be greatly appreciated.
Use the class as a selector $('.startButton') instead of the ID since ASP.Net controls change their IDs dynamically when rendered by appending its Page & Control information.
$(".startButton").fadeOut(500, callAlert);
Or, if you're adamant about using the ID, here is another way to handling the selector,
$("#<%=startButton.ClientID %>")
Or, as Jacob suggested in his answer, you could ClientIDMode="Static", but this works only if your application is .Net 4.0 or above.
Also, use CssClass instead of class
<asp:Button ID="startButton" Csslass="startButton" runat="server" Text="Click Me!" />
The first example has 2 problems.
1. You should write
$("#startButton").fadeOut(500, callAlert);
and not
$("#startButton").fadeOut(500, callAlert());
2. For ASP.NET you must set ClientIDMode="Static" ortherwise asp.net will alter your id.
<asp:Button ID="startButton" ClientIDMode="Static" ... OnClientClick="startButtonClick()"/>
How about the fact that your code is fine (although other answers here should be considered) but your button is making a post back to the server and simply your browser does not have enough time to render the fade effect.
To test this, add a return false; to the OnClientClick property. This will of course cancel your action on the server but you will obtain the fade effect:
<asp: Button ... OnClientClick="startButtonClick();return false;"></asp:Button>
To work around this and still submit your request, you can try to use the ASP.NET __doPostBack method in JavaScript
ASP.NET:
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick(this);return false;"/>
JavaScript:
function startButtonClick(button)
{
$("#startButtonSpan > input").fadeOut(500, function(){__doPostBack(button.name, "")});
}
The __doPostBack method takes two arguments: the name of the control that is doing the postback and a postback argument that can be use to send more info on the server. In the case of the asp:Button, the name of the button should be sufficient to send the request without a problem.
Using this technique you will fade the button on the client and also trigger the action on the server. I cannot guarantee that this exact code will work (I don't have access to a dev environment right now) but you should get the idea.
If I could, I would like to provide another answer for those that use MasterPages and find that you can't always use $("#<%= SomeContentControl.ClientID %>") when working with Content controls.
What I do is set the MasterPage ID in my Init() like this:
protected void Page_Init( object sender, EventArgs e )
{
// this must be done in Page_Init or the controls
// will still use "ctl00_xxx", instead of "Mstr_xxx"
this.ID = "Mstr";
}
Then, you can do something like this with your jQuery:
var masterId = "Mstr",
$startButton = getContentControl("startButton"),
$message = $("#jQueryTest");
function getContentControl( ctrlId )
{
return $("#" + masterId + "_" + ctrlId);
}
function hideStartButton()
{
$startButton
.stop(true, true)
.fadeOut("slow", showMessage);
}
function showMessage()
{
$message
.stop(true, true)
.fadeIn("slow");
}
$startButton.on("click", hideStartButton);
Here is a jsFiddle that has the Mstr_ prefix already inserted as if ASP.NET rendered it.

How to show a popup in primefaces with the requiredMessages, only if these messages exist?

I want to show a popup with the requiredMessages of some inputText fields when I click on a submit button. But just only in case of there are those messages. I have tried with bean variable and javascript on the oncomplete tag, but I'm not able to make it work properly. If I put visible="true" in p:dialog, the popup is always displayed, although I try to control it from the commandButton. Now, I have this, but the popup is never displayed:
<h:inputText id="Scheme"
required="true"
requiredMessage="Required.">
</h:inputText>
<h:commandButton id="submitModify" value="#{msg['systemdetail.modify']}"
action="#{sistem.modify}"
oncomplete="if (#{facesContext.maximumSeverity != null}) {dlg1.show();}">
</h:commandButton>
<p:dialog id="popup"
style="text-align:center"
widgetVar="dlg1"
modal="true">
<h:messages layout="table"/>
</p:dialog>
How can I do this? Thanks in advance.
Standard JSF and PrimeFaces does not support request based EL evaluation in on* attributes. RichFaces is the only who supports that. Besides, the standard JSF <h:commandButton> does not have an oncomplete attribute at all. You're probably confusing with PrimeFaces <p:commandButton>
There are several ways to achieve this:
Check the condition in the visible attribute of the <p:dialog> instead.
<p:dialog visible="#{not empty facesContext.messageList}">
or if you want to show validation messages only instead of all messages
<p:dialog visible="#{facesContext.validationFailed}">
Use PrimeFaces <p:commandButton> instead, the PrimeFaces JS API supports the #{facesContext.validationFailed} condition through the args object as well:
<p:commandButton ... oncomplete="if (args.validationFailed) dlg1.show()" />
If you need to check for what kind of messages, here is a way that I made work with primefaces. Since primefaces oncomplete is called after update, by updating the component holding the javascript function, the javascript function can be rebuilt using the latest #facesContext.maximumSeverity} values before executed.
<p:commandButton
oncomplete="executeAfterUpdate()"
update="updatedBeforeOnComplete"/>
<h:panelGroup id="updatedBeforeOnComplete">
<script language="JavaScript" type="text/javascript">
//
function executeAfterUpdate(){
if (#{facesContext.maximumSeverity==null
or facesContext.maximumSeverity.ordinal=='1'})
{
// your code to execute here
someDialog.show();
}
}
//
</script>
</h:panelGroup>

Simple JavaScript problem: onClick confirm not preventing default action

I'm making a simple remove link with an onClick event that brings up a confirm dialog. I want to confirm that the user wants to delete an entry. However, it seems that when Cancel is clicked in the dialog, the default action (i.e. the href link) is still taking place, so the entry still gets deleted. Not sure what I'm doing wrong here... Any input would be much appreciated.
EDIT: Actually, the way the code is now, the page doesn't even make the function call... so, no dialog comes up at all. I did have the onClick code as:
onClick="confirm('Delete entry?')"
which did bring up a dialog, but was still going to the link on Cancel.
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<script type="text/javascript">
function delete() {
return confirm('Delete entry?')
}
</script>
...
<tr>
<c:if test="${userIDRO}">
<td>
<a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}"/>" />
<img src="images/edit.GIF" ALT="Edit this skill." border="1"/></a>
</td>
<td>
<a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}&remove=1"/>" onClick="return delete()"/>
<img src="images/remove.GIF" ALT="Remove this skill." border="1"/></a>
</td>
</c:if>
</tr>
There's a typo in your code (the tag a is closed too early).
You can either use:
<img ...>
note the return (confirm): the value returned by scripts in intrinsic evens decides whether the default browser action is run or not; in case you need to run a big piece of code you can of course call another function:
<script type="text/javascript">
function confirm_delete() {
return confirm('are you sure?');
}
</script>
...
<img ...>
(note that delete is a keyword)
For completeness: modern browsers also support DOM events, allowing you to register more than one handler for the same event on each object, access the details of the event, stop the propagation and much more; see DOM Events.
Well, I used to have the same problem and the problem got solved by adding the word "return" before confirm:
onclick="return confirm('Delete entry?')"
I wish this could be heplful for you..
Good Luck!
I use this, works like a charm. No need to have any functions, just inline with your link(s)
onclick="javascript:return confirm('Are you sure you want to delete this comment?')"
I had issue alike (click on button, but after cancel clicked it still removes my object), so made this in such way, hope it helps someone in the future:
$('.deleteObject').click(function () {
var url = this.href;
var confirmText = "Are you sure you want to delete this object?";
if(confirm(confirmText)) {
$.ajax({
type:"POST",
url:url,
success:function () {
// Here goes something...
},
});
}
return false;
});
Using a simple link for an action such as removing a record looks dangerous to me : what if a crawler is trying to index your pages ?
It will ignore any javascript and follow every link, probably not a good thing.
You'd better use a form with method="POST".
And then you will have an event "OnSubmit" to do exactly what you want...
First of all, delete is a reserved word in javascript, I'm surprised this even executes for you (When I test it in Firefox, I get a syntax error)
Secondly, your HTML looks weird - is there a reason you're closing the opening anchor tags with /> instead of just > ?
<img src="images/delete.png" onclick="return confirm_delete('Are you sure?')">
<script type="text/javascript">
function confirm_delete(question) {
if(confirm(question)){
alert("Action to delete");
}else{
return false;
}
}
</script>
If you want to use small inline commands in the onclick tag you could go with something like this.
<button id="" class="delete" onclick="javascript:if(confirm('Are you sure you want to delete this entry?')){jQuery(this).parent().remove(); return false;}" type="button">
Delete
</button>
try this:
OnClientClick='return (confirm("Are you sure you want to delete this comment?"));'
I've had issue with IE7 and returning false before.
Check my answer here to another problem: Javascript not running on IE

Categories