I make a webmethod call and get an answer from the server if the current user can/can't print a document.
If the user can print, I want to display a print button. Otherwise not.
Is there a way to add a print button to an existing "div" from a web method?
You should try something like this(sorry, not tested)
$.ajax({
type: "POST",
url: "/yourPage.aspx/YourWebMethod",
data: "{yourParameterName:'" + yourparamvalue + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
var element = document.createElement("input");
element.setAttribute("type", "button");
element.setAttribute("value", "invert");
element.setAttribute("name", "button3");
element.setAttribute("onclick", "foo()");
var targetElement = document.getElemanById('yourdivid');
targetElement.appendChild(element);
},
error: function () { alert('/yourPage.aspx/YourWebMethod'); }
});
You dont need to add from web method, simply add button where ever you want to show, make sure it is hidden by default. check the value return from page method and show/hide button based on value.
PageMethods.CheckPermission(function (flag) {
if (flag == "1")
$("#btnPrint").show();
else
$("#btnPrint").hide();
});
Related
I'm using JScript + ASP.NET. I got a form with 2 inputs (user and password) and a button. What I'm trying to do is to:
1- Fire a click event
2- Look inside a database if the user exist
3- Give back the answer
4- If the answer is true, POST some data to an other page AND redirect to it.
I first tried to do this with ASP.NET. To POST data with ASP.NET I need to use PostBackUrl property, but the problem is that PostBackUrl ignore my click event.
I then tried to do this with jscript. On my click event (jquery), I use $.ajax to POST data to access my database, give the answer back in json...and I'm stuck there. In both method, I'm stuck at point 4.
ASP.NET
protected void SignIn_OnClick(object sender, EventArgs e)
{
Clients client = (Clients)clientDAO.getUsername(text1.Text, password2.Text);
if (client != null)
{
Session.Add("SessionNoClient", "1272");
Session.Add("CurrentQuote", "-1");
Session.Add("UnitSystem", "0");
Session.Add("SessionAdministrator", "0");
//How to redirect with POST here
}
}
JScript:
$("#m_bLogin").click(function () {
var username = $("#text1").val();
var password = $("#password2").val();
var form = $("#formClient");
$.ajax({
url: '../../Class/LoginAjax.asmx/GetLoginInformation',
data: "{ 'Name':'" + username + "','Password':'" + $("#password2").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//My Json returns {"'Name':'Bob','Password':'1234'} and I'm not able to access Name or Password property. I tried data.d, data.d.Name, eval(data.d.Name) etc...
form.submit();
},
error: function (XMLHttpRequest, textStatus, error) {
alert(error);
}
});
});
You could do something like that:
$.ajax({
url: '../../Class/LoginAjax.asmx/GetLoginInformation',
data: "{ 'Name':'" + username + "','Password':'" + $("#password2").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//My Json returns {"'Name':'Bob','Password':'1234'} and I'm not able to access Name or Password property. I tried data.d, data.d.Name, eval(data.d.Name) etc...
form.submit();
},
error: function (XMLHttpRequest, textStatus, error) {
alert(error);
}
}).done(function() {
window.location.href = "YourNewPage.aspx";
});
$(function () {
$("#tbNominalAccounts").autocomplete({
source: function (request, response){
$.ajax({
url: "TestPage3.aspx/GetUserNominalAccounts",
type:"POST",
datatype:"json",
data :{ searchText : request.term},
success: function(data)
{
response(
$.map(data, function(item)
{
return { label: item.NominalAccount, value:item.NominalAccount, id:item.NominalAccount}
}))
}
})
}
});
});
Added breakpoints and it hits the ajax call but when i put a breakpoint on the method GetUserNominalAccounts it doesent even reach it!! Any ideas of why its not posting?!
I have a textbox with an ID of #tbNominalAccounts just for background information
Reformat your data like so:
pString = '{"searchText":"' + request.term + '"}';
$.ajax({
data: pString,
...
and your server side code should have been properly "decorated" to allow page access.
Thought I would add some code from a working sample using asp.net: you might need this converter for generic handling of the asp.net data:
dataType: "jsond",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
EDIT: And for the use of the return value:
focus: function(event, ui)
{
return false; // return "true" will put the value (label) from the selection in the field used to type
},
try putting a contentType in the ajaxRequest:
contentType: "application/json; charset=utf-8",
I've noticed that when using jQuery Ajax the default content Type application/x-www-form-urlencoded doesn't work well enough.
I am using Jquery Ajax to set the values of a Label and a ListBox in my form. I realize that values are set properly by the function. But just after that , the page just refreshes clearing all previously set values . Why is this happening ? Iam new to Jquery/Ajax. Am I missing any fundamentals here ? Thanks in Advance.
Iam pasting the entire code
$(document).ready(function () {
$('#Button1').bind('click', function clk() {
$.ajax({
type: "POST",
url: "WebForm5.aspx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d.ListBox.length);
for (var i = 0; i < result.d.ListBox.length; i++) {
alert(result.d.ListBox[i]);
$(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
.appendTo('#<%=ListBox1.ClientID %>');
$('#Label1').text(result.d.MyProperty);
}
}
});
})
});
Button1 in your code is an asp button which is a submit button. When you click on it, it will submit the page and refresh the whole page. If you want to stop the page from being submitted on button click return false, it will work.
$('#Button1').bind('click', function clk() {
$.ajax({
type: "POST",
url: "WebForm5.aspx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d.ListBox.length);
for (var i = 0; i < result.d.ListBox.length; i++) {
alert(result.d.ListBox[i]);
$(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
.appendTo('#<%=ListBox1.ClientID %>');
$('#Label1').text(result.d.MyProperty);
}
}
});
return false;
})
i have a couple of queries regarding the fullcalendar by arshaw..
when i select a particular stretch of dates and give an appropriate title as shown here
i get the event rendered in the calendar.. but when i want to save the event (I'm using asp.net) ie say after the user clicks on a save button,the title,startdate,end date has to be written into the events[{}] of the script..for this im using
response.write("script /script(with the tags of course)") after the button click which doesnt work.. would anyone suggest a better or a simpler working way?
also how to disable the selectable property? eg only an admin can set the event and a user can only see the event and not edit it..
I don't think that you can update fullcalendar event JavaScript object with Response.Write() method.
You should use ajax to save event on server side and update calendar on client side.
Do something like this
function saveEvent() {
var event = { startDate: $('#txtDate').val(), description: $('#txtDescription').val(), id: id }
$.ajax({
type: "POST",
async: false,
url: "../UserCalendarService.asmx/SaveEvent",
data: "{'startDate': '" + event.startDate + "','description':'" + event.description + "','id':'" + event.id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
result = result.d;
eventFound = $('#calendar').fullCalendar('clientEvents', result.id).length;
if (eventFound == 1) {
existingEvent = $('#calendar').fullCalendar('clientEvents', result.id);
existingEvent[0].title = result.title;
existingEvent[0].start = result.start;
existingEvent[0].editable = result.editable;
existingEvent[0].allday = true;
$('#calendar').fullCalendar('updateEvent', existingEvent[0]);
}
else {
$('#calendar').fullCalendar('renderEvent', {
title: result.title,
start: result.start,
id: result.id,
editable: result.editable,
allday: true
},
false // make the event "stick"
);
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
if (err.Message == 'SomeErrorMessage') {
//handleError, redirect or popup message
}
}
});
}
As for your second question, event object has editable property. It is true or false.
You can found more about it in proper documentation.
I was wondering if it is possible to pass the forms collection from within an ajax method in jQuery?
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});
If it is possible to pass in the forms collection then when it arrives at the method within c# how to you read it in?
You can do something like this:
var form = $("#myForm").serialize();
$.post("/Home/MyUrl", form, function(returnHtml)
{
//callback
});
Then on the C# side you should be able to do something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyUrl(FormCollection collection)
{
//do what you gotta do
}
I think this should work.
EDIT: I just noticed that I simply assumed you were referring to ASP.NET MVC. If not, let me know as this answer is specific to MVC.
You can use the Ajax.BeginForm method from ASP.NET MVC. It will use Microsoft's ajax to do the request, but you can have a JQuery method execute upon completion. Or you can use an UpdatePanel and register a javascript to run with the ScriptManager once the UpdatePanel loads. Another thing you could try is using a jquery like the following: $(':input') to get a collection of all input, textarea, select and button elements(JQuery documentation), and pass that as the data into your request.
Got this working all okay, and it returns the input form collection in the FormCollection
input = $(':input')
$.ajax({
type: "POST",
url: "/page/Extension/" + $("#Id").val(),
data: input,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").html(msg);
false;
}
});