Events still not showing up despite the many tries...sigh - fullcalendar

I have tried the recommendation from this forum and through the many google searches...but i still can't get the events to show up on my calendar via jsp....i tried with php and it worked...sigh...i wonder where is the error....sigh....
The processRequest method is fine but when it dispatches to the JSP page...nothing appears from the browser....
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String email=request.getParameter("email");
try {
ArrayList<CalendarEvt> calc=CalendarDAO.retrieveEvent(email);
for (CalendarEvt calendarEvt : calc) {
System.out.println(calendarEvt.getEventId());
}
request.setAttribute("calendar", calc);
request.getRequestDispatcher("calendar.jsp").forward(request, response);
} catch (Exception e) {
}
}
Here is the JSP section that's giving me headaches...(Without the loop...the Google link does appear...)...I have tried putting quotations and leaving them out....still no luck:
<%--Load user's calendar--%>
<script type='text/javascript'>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
editable: false,
events: [
<c:forEach items="calendar" var="calc">
{
title: '${calc.eventName}',
start: ${calc.eventStart}
},
</c:forEach>
{
title: 'Click for Google',
start: new Date(y, m, 1),
end: new Date(y, m, 1),
url: 'http://google.com/'
}
]//end of events
});
});
</script>
<%--Load user's calendar--%>
...any kind of help would be greatly appreciated...thx!!

First you need to verify that the format is correct, and that jsp is outputting it correctly.
Perhaps create a dummy page, that just output's event data.
Also in your loop, not sure how you do it in JSP, but don't you need to not end with a comma, if your at the last item in the set of data?
Or maybe you can use your jsp to create a javascript array, that holds the data, that comes from JSP. then lower down, do the jQuery FullCalendar call, and pass that array full of data.
So you can either case, verify the correctness of the event data syntax/format and better ways to put the data inside the calendar call.
Good luck..

Related

ASP Razor: QuerySingle wrongly returns the same result

This piece of code should periodicaly request data from database:
<script type="text/javascript">
function refreshData() {
#{
var db2 = Database.Open("StarterSite");
string tresc2 = db2.QuerySingle(someQuery, 1).RoleName;
<text>
alert("#tresc2");
</text>
}
}
setInterval(function() {refreshData()}, 5000);
What I do is:
I run this code
I change value in the database
I expect to see alert with data changed
The problem is that alert displays the same value over and over again even once it changed.
What do I do wrong here?
Thank you
That's because the alert will never change. MVC renders the text when the request is made as
alert("whatever the value is on the first attempt");
If you hit view source in your browser, you'll see that in the HTML. In order to actually get the new values, you'll have to go back down to the server with some ajax.
First, setup your json result in a controller:
public JsonResult GetNewResult()
{
var db2 = Database.Open("StarterSite");
string tresc2 = db2.QuerySingle(someQuery, 1).RoleName;
return this.Json(tresc2);
}
Then query it:
$.ajax({
url: "/Controller/GetNewResult",
context: document.body
}).done(function(data) {
alert(data);
});

AJAX call returns page HTML / doesn't hit Page Method is ASP.Net (no MVC or Json)

I am updating a tool for my current company that provides basic product layout documents depending on choices picked. Recently it appears a bot of some sort has been hitting the toolbox periodically, and after some discussion with the company we built the toolbox for we have decided to add the ReCaptcha tool to the page.
The way the toolbox was setup is ASP.net without the use of Json or MVC (the toolbox is a fair few years old, built long before I joined the team). Adding the ReCaptcha tool was not an issue, I did it without a plugin using a window.onload function and using their instructions. This was all done on the options.aspx page, the code for the ReCaptcha call is in the options.aspx.cs page.
To reach this code I am attempting to do an AJAX call where the form would normally be submitted.
The issue: Each AJAX call returns the HTML of the page, and the Page Method (VerifyReCaptcha) does not trigger when I have a break point in it. I need it to call the method which will do all of the listing, then simply pass back a string that simply says if it was a success or not. It doesn't seem to matter what dataType or contentType I enter (if any), or if I run it as POST or GET.
Here is the code of the button that calls the function for the ajax call.
<input type="button" id="DownloadLayoutButton" value="Download Layout" class="navigationButton" style="width: 200px; height: 24px;" />
Here is the function that is called.
$("#DownloadLayoutButton").click(function () {
$.ajax(
{
url: "options.aspx/VerifyReCaptcha",
dataType: "text",
data: {
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
type: "POST",
success: function (result) {
if (result == "Success") {
alert("Success!");
else
alert("ReCaptcha entry was incorrect!");
},
error: function (request, status, error) {
alert("Error!");
}
});
});
This code never seems to hit the VerifyReCaptcha() method that is on the options.aspx.cs page, the method is as follows. As stated I have tested and confirmed that this function works on its own. Previously I had it returning a boolean value but since ajax can't work with booleans, I changed it to return "Success" or "Failure" depending on the result.
[WebMethod]
public static string VerifyReCaptcha(string challenge, string response)
{
try
{
string PRIVATE_KEY = "MY_KEY_HERE";
string remoteip = HttpContext.Current.Request.UserHostAddress;
WebRequest request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}", PRIVATE_KEY, remoteip, challenge, response));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataBytes.Length;
request.GetRequestStream().Write(dataBytes, 0, dataBytes.Length);
String resultString = String.Empty;
String errorString = String.Empty;
using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
{
resultString = sr.ReadLine();
errorString = sr.ReadLine();
}
Boolean b;
b = Boolean.TryParse(resultString, out b) && b;
if (b)
return "Success";
else
return "Failure";
}
catch (Exception)
{
return "Failure";
}
}
The aspx page is using the following sources.
<script type="text/javascript" src="JS/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="JS/jquery-validate/jquery.validate.js"></script>
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
Your ASP.NET AJAX Page Method needs to be static.
You have:
public virtual string VerifyReCaptcha()
It needs to be:
public static virtual string VerifyReCaptcha()
Note: Read Why do ASP.NET AJAX page methods have to be static? for more information.
As I understand it, asp.net WebMethods expect posted data in JSON.
In your JavaScript jQuery Ajax call use dataType: "json" rather than dataType: "text".
I also add contentType: "application/json; charset=utf-8" as another option.
The WebMethod is not called if the doesn't find the correctly formatted data it expects.

ASP.NET UpdatePanel cause full postback after idle

I'm using multiple updatepanels in my SharePoint Visual Web Parts. Everything is working fine until I leave the page to idle for a while.
For example if I change a few drop downs and leave the page to idle for about 5 minutes. Coming back to the page and changing a drop down will cause a full postback.
Another example is using a gridview with pagination. Leaving the grid view on page 5. Idle for 5 minutes and come back to the page. Clicking on page 8 for example will make the gridview go to page 1.
I am new to using Updatepanels and would really appreciate some advice.
I have solver this anonymous problem by adding this javascript. I have found that after some ideal time(~30sec) for each request it page goes for authenticate user. and if user is not authentication then it reload the whole page and re authenticate user that's why page is reload.
Add this java script code in your page which will solve your problem.
<script type="text/javascript">
var isNtlmActive = false;
var updatePannelsToUpdate = [];
var eventTarget = '';
var eventArgument = '';
var causesValidation = false;
var validationGroup = '';
var requestBody = '';
function initializeRequestHandler(sender, args) {
var onSuccess = function () {
//At this point the NTLM connection is re-established
var pageRequestManagerInstance;
isNtlmActive = true;
pageRequestManagerInstance = Sys.WebForms.PageRequestManager.getInstance();
// re-issuing the 'original' request
pageRequestManagerInstance.beginAsyncPostBack(updatePannelsToUpdate, eventTarget, eventArgument, causesValidation, validationGroup);
};
var onError = function () {
// do something here if error occurred
}
if (!isNtlmActive) {
// capturing and preserving the body as well as some other meta data about the original request
requestBody = args.get_request().get_body();
updatePannelsToUpdate = sender._postBackSettings.panelsToUpdate;
eventTarget = sender._postBackSettings.asyncTarget;
eventArgument = '';
causesValidation = false;
validationGroup = '';
// NOTE: the variable '_spFormOnSubmitCalled' is a global variable that gets injected by the logic iplemented in the 'init.js' file.
// Based on our observation of the logic in 'init.js' the varialbe '_spFormOnSubmitCalled' is set to true when HTML form's
// 'onsubmit' function is called and it is never set back to false (after we cancel the postback)
// As the result, any subsequent attempts to submit the form do not work.
// Thus, we excplicetely set the value back to false before we cancel the original post back request.
//
//'init.js'is autoatically referenced by SharePoint and included on to the 'master' page.
// The HTML form as well as the functionality to handle submit is also provided by SharePoint.
if (typeof _spFormOnSubmitCalled === "boolean") {
_spFormOnSubmitCalled = false;
}
args.set_cancel(true);
callServerSideServiceToReviveNtlmSession(onSuccess, onError);
}
else {
// resetting the body of the request with the value captured from the original request
args.get_request().set_body(requestBody);
isNtlmActive = false;
updatePannelsToUpdate = [];
eventTarget = '';
eventArgument = '';
causesValidation = false;
validationGroup = '';
}
}
function getCurrentSiteCollectionUrl() {
var url;
url = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
return url;
}
function callServerSideServiceToReviveNtlmSession(successHandler, errorHandler) {
var siteCollectionUrl;
var testServiceUrl;
var spRequestExecutor;
var request;
siteCollectionUrl = getCurrentSiteCollectionUrl();
testServiceUrl = siteCollectionUrl + "/_api/web/title";
spRequestExecutor = new SP.RequestExecutor(siteCollectionUrl);
request = {
url: testServiceUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
};
spRequestExecutor.executeAsync(request);
}
try {
$(document).ready(function () {
try {
var pageRequestManagerInstance = null;
//Note: Sys.WebForms.PageRequestManager gets injected into your page the minute you use ScriptManager (and UpdatePanel)
pageRequestManagerInstance = Sys.WebForms.PageRequestManager.getInstance();
pageRequestManagerInstance.add_initializeRequest(initializeRequestHandler);
}
catch (ex) {
//alert('INNER EXCEPTION: document ready - ' + ex.message);
}
});
}
catch (ex) {
//alert('EXCEPTION: document ready - ' + ex.message);
}
</script>
Mark as answer if this answer found helpful...
Thanks..!!
Enable or disable session state across the entire farm
On the taskbar, click Start, point to Administrative Tools, and then click SharePoint 3.0 Central Administration.
In the top navigation bar, click the Application Management tab.
On the Application Management page, in the Office SharePoint Servers Shared Services section, click Configure session state.
On the Configure Session State page, in the Enable Session State section, select the Enable Session State check box to enable session state for the farm.
To specify the duration of sessions, in the Timeout section, enter a number (in minutes) in the Session should be timed out after (minutes) box. The default is 60 minutes.
Click OK to save the session state configuration.
This one will give you more guidance
http://technet.microsoft.com/en-us/library/cc263527.aspx
if any confusion ask me,

open a new window of view when call controller from Jquery Ajax post call

I'm using ASP.Net MVC2. I'm trying to open a new window of view when call controller from Jquery Ajax post call.
here is my code..
in ascx page..
$('#DeleteButton').click(function () {
var isLineChecked = $(':checkbox:checked', '#providerSearchResultsTable').length;
if (isLineChecked == 0) {
alert("Please select at least one row ");
return false;
}
else {
var params = {
Id: gaiSelected.join(',')
};
alert(params);
$.ajax({
type: "Post",
url: "SelectProviderAndContact",
data: params,
success: function (html) {
**//$('#SelectProviderAndContact').html(html);**
}
});
}
});
here is my controller Action method
[SessionFilter]
public ActionResult SelectProviderAndContact(string Id)
{
try
{
List<ProviderBaseInfo> providerList = null;
string[] internalProviderIDs = Id.Split(",".ToCharArray());
//string[] billingProviderNames = billingProvider.Split(",".ToCharArray());
IStateBag stateBag = _commonModel.GetStateBag();
//stateBag.SetValue("InternalProviderId", Id);
List<Guid> internalProviderIds = new List<Guid>();
foreach (var a in internalProviderIDs)
{
internalProviderIds.Add(new Guid(a));
}
List<Contacts> providerContactList = _providerModel.GetProviderContactlist(internalProviderIds);
if (providerContactList.Count <= 0)
{
//IStateBag stateBag = GetStateBag();
List<ProviderBaseInfo> providers = (List<ProviderBaseInfo>)stateBag.GetValue(ProviderListCache);
if (providers == null)
{
providerList = _providerModel.GetProviderCompleteList(null, null, null, null, Id).ToList();
}
else
{
providerList = providers.Where(x => internalProviderIds.Contains(x.InternalProviderId)).ToList();
}
providerContactList = _providerModel.GetContactlistbyInsertingProviders(providerList);
}
ViewData["ProviderNotFound"] = false;
// ViewData["ProviderName"] = new SelectList(billingProvider.Select(x => new { value = x, text = x }), "value", "text");
var Provider = new[] {
new { ProviderId = "A", Providername = "A" }
//new DataContracts.RegionKeyValues { RegionId = "B", RegionValue = "B" },
//new DataContracts.RegionKeyValues { RegionId = "D", RegionValue = "D" }
};
ViewData["ProviderName"] = new SelectList(Provider, "ProviderId", "Providername");
**return View("SelectProviderAndContact",providerContactList);**
}
catch (FaultException<MedicareFault> ex)
{
if (ex.Code.Name == typeof(ArgumentException).Name)
{
ViewData["ProviderNotFound"] = true;
ViewData["Error"] = ex.Reason;
return View((object)null);
}
else
{
ViewData["Error"] = Errors.Common.UnknownError;
return View((object)null);
}
}
catch
{
ViewData["Error"] = Errors.Common.UnknownError;
return View((object)null);
}
}
and I have created SelectProviderAndContact.aspx in view.
Please any one help me to open another window with SelectProviderAndContact.aspx
from ajax post call.
Your jquery will have to do almost all the work in opening a window. Using the window.open() method in your javascript you can make your controller send back a specific argument that causes it to open a new window with a certain URL (i.e. TheSmallPopupPageThatViewsResults.aspx?resultId=12345 or something).
Your controller would just decide whether or not to tell the view to open the new window and the view would then open it if it is told to.
With your specific implementation, you may have to create a model or something that stores results in the database so that the controller can save the result and the action and view that are for the popup page can then access that result. Another way of doing it would be to have the arguments that the popup page is called with determine what is viewed on the page. This would eliminate the need for another model, but your urls could get really long really fast if you have a lot of data and I believe that there is generally a limit to how long those urls can be.
I would recommend using JSON or XML to return the data to the javascript so that you can extend the returned object as much as needed. The way I have done it in the past is made several XML tags like <alert>, <refresh>, <redirect>, <somePageSpecificAction>, etc that I have jquery parse using $(theEnclosingTag).each( function () { //...parse here }).
I use mainly MVC3 so I don't know if this is supported in MVC2, but changing ActionResult to JsonResult for the return type and using return this.Json(new { put = "data here" }); for your return statements makes it really easy to use json.
Also, It may be beneficial to use a different action method to process ajax requests. You would then have one action that displays the page, another action to process ajax requests from that page (it could be decorated with [HttpPost] or something), and another method for your popup page view. That would also keep your code short and easier to read. Having long controller methods can get really confusing later down the line when you try to find the location of a specific bug.
EDIT: A specific example: Assuming MVC3 (since that is what I use...I think you can find other ways of doing this...you could use an xml serializer and just output xml) you have your page (Action #1) that displays with all your buttons and stuff (this is where you javascript containing the $("#DeleteButton") and such goes as well). Your javascript makes its AJAX call to another action (SelectContactAJAX or something...this is action #2) with a few arguments which has a return type of JsonResult. Your javascript gets the response back from that ajax-specific action and the response tells it "open a window with the URL /SelectContactForm?choiceId=12345" (or something). The choiceId is a reference that would be used in the background for the SelectContactForm action (yet another separate action...action #3) to know what to display. Your ajax would then call window.open("/SelectContactForm?choiceId=12345") and when the window opens, it calls action #3 which looks up the reference for what it should be displaying and then shows that to the user.
As for getting feedback on what the user entered in the new window and having the original page react, there are various ways in javascript to listen for window closings and such, but I haven't ever had to use this in one of my applications and it is a bit out of the scope of this question.
use colorbox jquery plugin
http://www.jacklmoore.com/colorbox
write code in .aspx page to call .ascx page
parent.$.fn.colorbox({ href: '/IGTR/SaveIGTRPreference/' + id + '?t=' + Math.random(), height: "400", width: "800", overlayClose: false, escKey: false
});
Here SaveIGTRPreference is .ascx page

RedirectToAction not working when called by jQuery?

I am trying to call an action method by jQuery, and got help with passing parameters here: Calling action method in MVC with jQuery and parameters not working . However, even though the parameters are sent correctly now, in the action method I need to redirect (passing on those same parameters) to another action method. In the debugger I can see that the redirect is carried out, and the parameters are still there, but the View returned doesn't update accordingly...
Is there some problem with calling an action method that redirects by using jQuery?
Action method called by jQuery:
public ActionResult SelectDate(string date)
{
DateTime dateObject = DateTime.Parse(date);
MyCalendar calendar = new MyCalendar();
string number = calendar.GetWeekNumber(dateObject).ToString();
string year = dateObject.Year.ToString();
return RedirectToAction("Edit", new { number = number, year = year });
}
Action method redirected to:
public ActionResult Edit(string number, string year) //Why string here???
{
int n;
if (string.IsNullOrEmpty(number))
n = myCalendar.GetWeekNumber(DateTime.Today);
else
n = Int32.Parse(number);
int y;
if (string.IsNullOrEmpty(year))
y = DateTime.Today.Year;
else
y = Int32.Parse(year);
List<Customer> customers = _repository.Customers;
ViewData["Customers"] = new SelectList(customers, "CustomerId", "CustomerName");
ViewData["WeekNumber"] = n;
ViewData["Year"] = y;
return View();
}
Or is jQuery get() not the proper way to call an action method to load a new page? Note that doing the same thing with an ActionLink works fine, it's just that I need to call it by jQuery because I'm using the datepicker plugin and also a button as the way to call the action.
What am I doing wrong?
UPDATE:
Actually, the RedirectToAction doesn't seem to be the problem, I modified the code so that the jQuery now calls the final action method directly (by doing the job of the first action method directly in the jQuery, i.e. convert date to week and year). But I still don't get the new page with the new week and year.
Here's the new jQuery:
function selectWeek() {
$('#selectWeekButton').click(function (event) {
var date = $('#selectWeekId').val();
var selectedDate = new Date(date);
var year = selectedDate.getFullYear();
var week = selectedDate.getWeekOfYear();
var url = '<%: Url.Action("Edit") %>';
$.get(url, { number: week, year: year }, function (data) {
// alert('Test');
});
});
}
Again, is it using the get that is incorrect? I do not wish to load content in an html tag, I just want to use jQuery to do the exact same thing as an actionlink, i.e. call an action method to get the Edit View...
For instance, this actionlink works fine, calling an action method called Next that redirects to Edit and shows the new week and year View:
<a href="<%=Url.Action("Next", new { number=ViewData["WeekNumber"], year = ViewData["Year"] })%>">
>></a>
But I want to do that (or Edit directly) in jQuery...
jquery AJAX automatically follows redirect meaning that in the success callback you will get the result of the Edit action you have redirected to. In this callback you will get the partial HTML returned by the controller action. So if you want to update some part of the DOM you need to explicitly instruct it so:
$.ajax({
url: '<%= Url.Action("SelectDate") %>',
data: { date: '123' },
success: function(result) {
$('#someresultDiv').html(result);
}
});
or simply use the .load() method:
$('#someresultDiv').load('<%= Url.Action("SelectDate") %>', { date: '123' });

Resources