Im using this cool javascript scheduler. At first I load it in my page by
function get_dependencies() {
//event calendar
$(".myscheduler").dhx_scheduler({
xml_date: "%Y-%m-%d %H:%i",
date: new Date(2014, 4, 25),
mode: "month"
});
scheduler.load($("body").attr("data-link") + "/core/plugins/dhtmlcalendar/events.xml");
}
and then call the function
$(window).load(function(){
get_dependencies();
});
and then when any of navs is click (navs associated with the ajax page stuff) call the page and render the scheduler again
$.ajax({
url: '/ajax-page',
type: 'post',
dataType: 'html',
beforeSend: function () {
$("#loading").show();
},
data: {
page: this_tab_content_link,
_token: $("body").attr("data-token")
},
success: function (data) {
$(".active_tab_content").html(data);
if ($(this).hasClass("reload_dependencies")) {
get_dependencies();
}
$("#loading").hide();
}
});
but sadly the scheduler, didn't render (no calendar scheduler is showing) after the html data (the ajax page response) is put in to the specified container. Any ideas, help, suggestions, recommendations, help?
Set relevant context to ajax callback, this in your code is jqXHR option object. Set ajax option context to this:
$.ajax({
context: this,
/*...*/
});
Related
I'm using jquery DataTables to show some tabular data, and I also placed an edit link for each row in said jquery DataTables so that the user can edit data associated with a particular row if needed. ( Also, I have No clue how to use ASP.NET MVC Html helpers within jQuery DataTables so that is why I am using the html link in the following code )
jquery DataTable javascript:
$("#resultCodeTable").dataTable({
"processing": true,
"serverSide": false,
"destroy": shouldDestroy,
"ajax": {
"url": "../Admin/LoadResultCodes",
"type": "GET",
"datatype": "json",
"data": function (data) {
data.actionCodeIDArg = actionCodeIDInQuestion;
}
},
....................................
............................
..............
columnDefs: [
{
{
targets: 1,
searchable: false,
orderable: false,
name: "EditResultCodeInQuestionReasonForArrears",
"data": "ID",
render: function (data, type, full, meta) {
if (type === 'display') {
data = '<a class="editResultCodeInQuestionReasonForArrears" href="javascript:void(0)" data-id="' + full.ID + '">Edit RFAs</a>'
}
return data;
}
},
....................................
............................
..............
Clicking on the aforementioned link will ensure that the point of execution reaches the following jQuery Event Handler method:
jQuery Event handler method/ function Javascript
$('#resultCodeTable').on('click', '.editResultCodeInQuestionReasonForArrears', function () {
console.log(this.value);
navigateToAParticularResultCodeAssociatedReasonForArrearsList($(this).data('id'));
});
The jQuery Ajax call successfully invokes the C# Controller's action because I see the Visual Studio's Debugger's point of execution reach said Controller's action, however, it fail to navigate to the view that I want to show.
jquery / javascript:
function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) {
console.log(resultCodeTable_ID);
$.ajax({
url: '../Admin/NavigateToAParticularResultCodeAssociatedReasonForArrearsList',
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}",
cache: false,
}).done(function (response, status, jqxhr) {
})
.fail(function (jqxhr, status, error) {
// this is the ""error"" callback
});
}
C#: ( in my AdminController.cs )
public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel();
aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg;
return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel);
}
Razor / Html: (In my \Areas\Admin\Views\Admin\AdminModules\Auxiliaries\AParticularResultCodeAssociatedReasonForArrearsList.cshtml view )
#model Trilogy.Areas.Admin.ViewModels.Auxiliaries.AParticularResultCodeAssociatedReasonForArrearsListViewModel
#{
ViewBag.Title = "AParticularResultCodeAssociatedReasonForArrearsList";
}
<h2>AParticularResultCodeAssociatedReasonForArrearsList</h2>
Could someone please tell me how I can change the code so that the view shows up after the jquery Ajax invocation?
May be on .done function you will get the view in the response, you need to take that response and bind it to your control
You call the controller via AJAX, and sure it hits the controller action method, and the controller returns a view but this is your code that deals with whatever is returned from the AJAX call (from the controller):
.done(function (response, status, jqxhr) {})
You are doing absolutely nothing, so why would it navigate anywhere.
A better question you need to ask yourself, instead of fixing this, is why would you use AJAX and then navigate to another page. If you are navigating to a whole new page, new URL, then simply submit a form regularly (without AJAX) or do it via a link (which the user will click). Use AJAX post if you want to stay on the same page and refresh the page's contents.
#yas-ikeda , #codingyoshi , #code-first Thank you for your suggestions.
Here are the modifications that I had to make to resolve the problem(please feel free to suggest improvements):
Basically, I had to end up creating 2 separate Action methods to resolve the problem.
In the jquery/Javascript code below, it is important to note the first action method '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList'
function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) {
console.log(resultCodeTable_ID);
$.ajax({
url: '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList',
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}",
cache: false,
}).done(function (response, status, jqxhr) {
window.location.href = response.Url;
})
.fail(function (jqxhr, status, error) {
// this is the ""error"" callback
});
}
The purpose of the 1st action method called '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList' is to retrieve a url within a Json object.
[HttpPost]
public ActionResult RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
var redirectUrl = new UrlHelper(Request.RequestContext).Action("NavigateToAParticularResultCodeAssociatedReasonForArrearsList", "Admin", new { resultCodeTable_IDArg = resultCodeTable_IDArg });
return Json(new { Url = redirectUrl });
}
The purpose of the 2nd action method is to ultimately navigate to the ASP.NET MVC View that I want to show.
public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel();
aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg;
aParticularResultCodeAssociatedReasonForArrearsListViewModel.RFACodeList = actionCodeResultCodeBusinessService.GetSpecificResultCodeRFACodeList(resultCodeTable_IDArg);
return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel);
}
However, I Dislike the fact that I have to use 2 action methods to navigate to the desired asp.net mvc view, therefore, please feel free to suggest improvements or even a totally different better solution.
I have a page which loads multiple tables separated by TAB using bootstrap.
In the third tab called patient tab, I have an action being done inside a modal.
An ajax call in the view will call an action in controller, when the logic successfully returned to the view, it will call an alert box and to load the latest result set in the table, I put location.reload() function, HOWEVER, the page returns or load in the first TAB and not in the 3rd where I do some action.
Can I specify or force the Tab to be loaded?
here the snippet of the ajax call in view, since it is quite long
}).promise().done(function () {
$.ajax({
type: 'POST',
url: '/Patient/SaveWeight',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(add_upd_obj_arr),
dataType: "json",
traditional: true,
success: function (result) {
if (result.errMsg == '' || result.errMsg == "") {
bootbox.alert({
size: "small",
title: "Confirmation!",
message: "Successfully Updated.",
callback: function () {
$('#ModalVitalSign').modal('hide');
location.reload();
}
});
} else {
bootbox.alert(result.errMsg);
}
},
error: function () {
bootbox.alert({
size: "small",
title: "Error!",
message: "There is an error while loading data."
});
}
});
});
I tried this, but does not refresh
window.location.hash = tab_treatment_info; //id of the third tab
I am using a jQuery plugin called Maplacejs (https://maplacejs.com/) to make Google Maps manipulation easier for me (I am new with this subject).
I first create a variable to set (initialize) Maplace:
var maplace = new Maplace({
map_div: '#mappanel',
controls_type: 'dropdown',
controls_title: 'Select a point:',
controls_position: google.maps.ControlPosition.TOP_LEFT
});
Then I create a function to load the locations in Maplace using ajax, when a certain date is selected in a dropdown menu:
function loadMap() {
$.ajax({
url: 'includes/ajax_getmap.php',
type: 'POST',
cache: false,
timeout: 5000,
data: { date: $('#dateselect').val() },
dataType: 'json',
success: function(data) {
maplace.SetLocations(data.locations, true);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown)
}
});
}
Here is an example of the locations array loaded with ajax:
{"locations":[
{"lat":52.1,"lon":11.3,"title":"Title 1","html":"<h3>Content 1</h3>","zoom":8},
{"lat":51.2,"lon":22.2,"title":"Title 2","html":"<h3>Content 2</h3>","zoom":8},
{"lat":49.4,"lon":35.9,"title":"Title 3","html":"<h3>Content 3</h3>","zoom":8},
{"lat":47.8,"lon":15.6,"title":"Title 4","html":"<h3>Content D2</h3>","zoom":8}
]}
And here is the code used to "call" the function (list of dates):
$('#dateselect').selectmenu({
style: 'dropdown',
change: function(event, data) {
loadMap();
}
});
The problem is: everytime this function is called, controls get duplicated in the map. Here is an example image after I call the function 3 times:
I already tried to create the maplace variable inside the ajax "sucess" event, and even set the variable to "null" or "undefined", but without sucess :(
Please, can you help me?
For whom have the same problem, it was an issue and was fixed by latest version 0.2.8 (March 2017). Download last version here.
When an POST is made to the controller, the controller responds with exactly what I want the browser to render. But the browser does not render the response. I've verified the response is good in Fiddler.
The code below shows what I think is relavent code. The controller action method that returns the response, part of the template that has the mvc helper code, javascript/jquery code that fires the ajax call with the form inputs.
I want to use the FormCollection. Why doesn't the browser render the response and what can I do to fix it?
BoMController
public ActionResult GetBillOfMaterialsView(FormCollection frmColl){
// snipped out model interaction
return PartialView("~/Views/Project/Index.cshtml", project);
}
Index.cshtml
#using (Html.BeginForm("GetBillOfMaterialsView", "BoM", FormMethod.Post, new {id = "frmGetBom"})) {
// selProj input select code removed for brevity
}
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize()
});
}
$(document).ready(function() {
$('#selProj').selectmenu( {
select: function(){submitGetBoM()}
}).addClass("overflow");
});
Invoking $.ajax alone doesn't append the response from the server to the document, you have to use the success callback to manually fetch the response and append it.
For example:
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function(response) {
$('#someContainerId').html(response);
}
});
Alternatively, use load() that is a shorthand to the above:
$('#someContainerId').load(frmGetBom.attr('action'), frmGetBom.serializeArray());
See Documentation
Your client code doesn't do anything with the returned values from the server:
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function() { alert('ok'); }
});
}
This would popup an alert on success.
I have 3 partial views with JS using JQuery in each to post a form and open a new partial view when the form is posted.
What I am finding is that the first time the JS fires it works fine but if I then go to post the form on the new page, I calls the function from the previous page.
The code:
$('#selector').click(function (e) {
var actionName = $(this).attr("id")
e.preventDefault();
e.stopImmediatePropagation();
alert("page1 js being called")
$('#page1Form').submit(function () {
$.ajax({
url: 'Dashboard/Page1/',
data: $(this).serialize(),
type: 'POST',
success: function () {
$.ajax({
url: 'Dashboard/LoadPartial',
data: { viewName: actionName },
type: 'GET',
success: function (d) {
$('#partial').html(d);
}
});
},
});
});
$('#page1Form').submit();
});
The second partial view has a function the same as that but only with the relevant selectors etc and for some reason the previous pages JS is being called as the alert alert("page1 js being called") is appearing in the browser!
Thanks in advance.
If you're loading partial views that means the entire page isn't being refreshed, and as a result the already loaded scripts will still be there. You'll need to remove the event handlers that correspond to the page1 content before adding the new content in:
$.ajax({
url: 'Dashboard/LoadPartial',
data: {
viewName: actionName
},
type: 'GET',
success: function (d) {
$('#selector').off('click'); // remove the click event handler
$('#page1Form').off('submit'); // remove the submit event handler
$('#partial').html(d); // add your new content
}
});