Handsontable autosave - ajax not defined - javascript

I copied the code from Handsontable official documentation, into a JSFiddle. This is handsontable 0.34.5.
I am getting an error in chrome console:
"ajax is not defined".
Code as follows, pre-loaded with handsontable.full.min.js and handsontable.full.min.css
HTML:
<div class="ajax-container">
<div class="controls">
<button name="load" id="load" class="intext-btn">Load</button>
<button name="save" id="save" class="intext-btn">Save</button>
<label>
<input type="checkbox" name="autosave" id="autosave" checked="checked" autocomplete="off">Autosave</label>
</div>
<pre id="example1console" class="console">Click "Load" to load data from server</pre>
<div id="example1" class="hot handsontable"></div>
</div>
Script:
var
$$ = function(id) {
return document.getElementById(id);
},
container = $$('example1'),
exampleConsole = $$('example1console'),
autosave = $$('autosave'),
load = $$('load'),
save = $$('save'),
autosaveNotification,
hot;
hot = new Handsontable(container, {
startRows: 8,
startCols: 6,
rowHeaders: true,
colHeaders: true,
afterChange: function(change, source) {
if (source === 'loadData') {
return; //don't save this change
}
if (!autosave.checked) {
return;
}
clearTimeout(autosaveNotification);
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: change
}), function(data) {
exampleConsole.innerText = 'Autosaved (' + change.length + ' ' + 'cell' + (change.length > 1 ? 's' : '') + ')';
autosaveNotification = setTimeout(function() {
exampleConsole.innerText = 'Changes will be autosaved';
}, 1000);
});
}
});
Handsontable.dom.addEvent(load, 'click', function() {
ajax('scripts/json/load.json', 'GET', '', function(res) {
var data = JSON.parse(res.response);
hot.loadData(data.data);
exampleConsole.innerText = 'Data loaded';
});
});
Handsontable.dom.addEvent(save, 'click', function() {
// save all cell's data
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: hot.getData()
}), function(res) {
var response = JSON.parse(res.response);
if (response.result === 'ok') {
exampleConsole.innerText = 'Data saved';
} else {
exampleConsole.innerText = 'Save error';
}
});
});
Handsontable.dom.addEvent(autosave, 'click', function() {
if (autosave.checked) {
exampleConsole.innerText = 'Changes will be autosaved';
} else {
exampleConsole.innerText = 'Changes will not be autosaved';
}
});

The code of the ajax function they are using is rather simple, is just a wrapper around XMLHttpRequest.
NOTE: I got it by just executing ajax.toString() via devtools on their docs page. It isn't referencing external functions, so it will work as is.
function ajax(url, method, params, callback) {
var obj;
try {
obj = new XMLHttpRequest();
} catch (e) {
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support Ajax.");
return false;
}
}
}
obj.onreadystatechange = function () {
if (obj.readyState == 4) {
callback(obj);
}
};
obj.open(method, url, true);
obj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
obj.send(params);
return obj;
}

Related

How to add Antiforgery protection to such asp.net-mvc application?

I have an old asp.net mvc project using JS. I need to add Cross-Site Request Forgery protection, but I don't know, how to implement it in my case.
Could somebody help me with this, please?
chtml-view:
#model WebGridResults<IndexingCollectionModel>
#{
ViewBag.Title = "Manage Collections";
Layout = "~/_Indexing.cshtml";
}
#section grid_options
{
<div class="km-grid-option-padding">
<ul class="inline pull-right">
<li>
<a id="kmid_removeSelected"
class="km-grid-option remove"
href="#Url.Action("DeleteSelected", "Indexing", new { Area = "Admin" })"
data-target="km_grid_body"
data-redirect="#Url.Action("ManageCollections", "Indexing", new { Area = "Admin" })"
data-actiontype="submit_selected"
data-message="Do you want to continue?"><i class="icon-remove"></i> Remove Selected</a>
</li>
</ul>
</div>
}
JS-part:
$("[data-actiontype='submit_selected']").bind("click",
function () {
var $this = $(this);
var message = $this.data("message");
KM.Ajax.ShowConfirmation({ title: "Warning", message: message }, function () {
var url = $this.attr("href");
var redirect = $this.data("redirect");
var targetId = $this.data("target");
var selected = [];
var SelectedItemsIds = GetSelectedItemsIds();
$.each(SelectedItemsIds, function (Key, Item) {
selected.push({ name: "selected", value: Item });
});
//THIS PART WAS ADDED BY ME *********
var token = $("input[name='__RequestVerificationToken']").val();
if(token !== undefined && token !== "")
selected.push({name: "__RequestVerificationToken", value: token});
//*****************
$.ajax({
type: "POST",
url: url,
data: selected,
success: function (result) {
if (typeof (result) == "object") {
var json = result || {};
if (json.Success) {
var $target = $("#" + targetId);
if( settings.fullPageLoad === true )
{
location.reload();
}
else
{
$target.load( redirect, function()
{
if( settings.reloadCallback )
{
settings.reloadCallback();
}
} );
}
}
}
},
dataType: "json",
traditional: true
});
});
return false;
});
Controller:
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult DeleteSelected(Guid[] selected)
{
try
{
_presenter.Delete(selected);
return Json(new { Success = true });
}
catch (Exception ex)
{
ModelState.AddModelError(ErrorRemoveSelected, ex.Message);
var errors = ModelState.ParseErrors();
return Json(new { Success = false, Errors = errors });
}
}
I've tried to add to request data (it is my part of code) in JS-function:
var token = $("input[name='__RequestVerificationToken']").val();
if(token !== undefined && token !== "")
selected.push({name: "__RequestVerificationToken", value: token});
Also I've added [ValidateAntiForgeryToken()] to controller method.
And it works, but only one time. When I try to perform the same action on the same page - it doesn't work.
What am I doing wrong?
Thank you in advanced!

Intermitient "Cannot reinitialise DataTable" error

I am making a project with a DataTable (https://datatables.net) and the issue I am having is pretty strange.
Sometimes when I load the page, everything works 100% and other times when I load the page I get this error from DataTables in a popup:
DataTables warning: table id=resdatatable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
As I have said, there's no sure fire way to trigger this. If I hit refresh sometimes it will work, sometimes it will give me that error.
I am not trying to reinitialize the DataTable, so I am a bit confused on why this is happening. I checked the link in the description but I am not understanding how to remedy this.
Here is my code:
let statusList = getStatusList();
function getRes(callback) { // ADDED CALLBACK
let city = document.getElementById("cityselect").value;
$.ajax({
type: 'get',
url: 'getreservationstable.php?city='+city,
dataType: 'json',
cache: false,
success: callback // USED CALLBACK
});
}
function changeCity()
{
$('#resdatatable').DataTable().ajax.reload();
}
getRes(function (result) { // APPLIED CALLBACK
$('#resdatatable').DataTable({
data: result, // YOUR RESULT
columns: [
{ data: 'id', title: 'ID' },
{ data: 'bookingdatetime', title: 'Booking Date' },
{ data: 'name', title: 'Name' },
{ data: 'class', title: 'Class' },
{ data: 'pickupdatetime', title: 'Pick up' },
{ data: 'duration', title: 'Duration' },
{ data: 'dropdatetime', title: 'Drop off' },
{ data: 'age', title: 'Age' },
{ data: 'coverage', title: 'Coverage' },
{ data: 'quote', title: 'Quote' },
{
data: 'status',
title: 'Status',
render: function(data, type, row) {
let isKnown = statusList.filter(function(k) { return k.id === data; }).length > 0;
if (isKnown) {
return $('<select id ="resstatus' + row.id + '" onchange="changeResStatus(' + row.id + ')">', {
id: 'resstatus-' + row.id, // custom id
value: data
}).append(statusList.map(function(knownStatus) {
let $option = $('<option>', {
text: knownStatus.text,
value: knownStatus.id
});
if (row.status === knownStatus.id) {
$option.attr('selected', 'selected');
}
return $option;
})).on('change', function() {
changeresstatus(row.id); // Call change with row ID
}).prop('outerHTML');
} else {
return data;
}
}
}
]
});
});
/**
* jQuery plugin to convert text in a cell to a dropdown
*/
(function($) {
$.fn.createDropDown = function(items) {
let oldTxt = this.text();
let isKnown = items.filter(function(k) { return k.id === oldTxt; }).length > 0;
if (isKnown) {
this.empty().append($('<select>').append(items.map(function(item) {
let $option = $('<option>', {
text: item.text,
value: item.id
});
if (item.id === oldTxt) {
$option.attr('selected', 'selected');
}
return $option;
})));
}
return this;
};
})(jQuery);
// If you remove the renderer above and change this to true,
// you can call this, but it will run once...
if (false) {
$('#resdatatable > tbody tr').each(function(i, tr) {
$(tr).find('td').last().createDropDown(statusList);
});
}
function getStatusList() {
return [{
id: 'Confirmed',
text: 'Confirmed'
}, {
id: 'Unconfirmed',
text: 'Unconfirmed'
}, {
id: 'Open',
text: 'Open'
}, {
id: 'Closed',
text: 'Closed'
}, {
id: 'Canceled',
text: 'Canceled'
}];
}
function changeResStatus(str1) {
var id = str1;
var status = document.getElementById("resstatus" + id).value;
var mailres = "";
var r = confirm("Change Status for ID # " + id + " to " + status + "?");
if (r == true) {
if (document.getElementById("resstatus" + id).value == "Confirmed"){
var s = confirm("Send ID # " + id + " a confirmation email?");
if (s == true) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").setAttribute ("data-notify-msg", this.responseText);
document.getElementById("result").setAttribute ("data-notify-type", "info");
SEMICOLON.widget.notifications(document.getElementById("result"));
}
};
xmlhttp.open("GET","sendconfirmationemail.php?id="+id,true);
xmlhttp.send();
}
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").setAttribute ("data-notify-msg", this.responseText);
document.getElementById("result").setAttribute ("data-notify-type", "info");
SEMICOLON.widget.notifications(document.getElementById("result"));
}
};
xmlhttp.open("GET","changeresstatus.php?id="+id+"&status="+status,true);
xmlhttp.send();
}else{
document.getElementById("result").setAttribute ("data-notify-msg", "Change status action aborted");
document.getElementById("result").setAttribute ("data-notify-type", "error");
SEMICOLON.widget.notifications(document.getElementById("result"));
}
}
$(document).ready(function() {
var table = $('#resdatatable').DataTable();
$('#resdatatable tbody').on('click', 'tr', function () {
var data = table.row( this ).data().id;
$.ajax({
type: 'POST',
url: 'getreservationsdetails.php',
dataType: 'json',
data: { id:data, },
success: function(response) {
$('#resulttitle').html("Booking ID # " + response[0].id);
$('#resdetname').html(response[0].name);
$('#resdetbdate').html(response[0].bookingdatetime);
$('#resdetadd').html("<br>" + response[0].address + "<br>" + response[0].city + "<br>" + response[0].state + " " + response[0].post);
$('#resdetphone').html(response[0].phone);
$('#resdetemail').html(response[0].email);
$('#resdetdln').html(response[0].dlnum);
$('#resdetdle').html(response[0].dlexp);
$('#resdetdlc').html(response[0].dlcountry);
$('#resdetpickup').html(response[0].pickuploc + " " + response[0].pickupdatetime);
$('#resdetduration').html(response[0].duration);
$('#resdetdrop').html(response[0].droploc + " " + response[0].dropdatetime);
$('#resdetclass').html(response[0].class);
$('#resdetcoverage').html(response[0].coverage);
$('#resdetage').html(response[0].age);
$('#resdetnumofdrivers').html(response[0].numofdrivers);
$('#resdetroadside').html(response[0].roadsideass);
$('#resdetafterhoursdrop').html(response[0].afterhoursdrop);
$('#resdetpromo').html(response[0].promo);
$('#resdetquote').html(response[0].quote);
$('#resdetaddcomments').html(response[0].name);
$('#resdetip').html(response[0].ip);
$("#modalresult").modal();
}
});
} );
} );
Edit:
Upon further examination, this error seems to be caused by the line var table = $('#resdatatable').DataTable(); in $(document).ready(function() { - if I remove that line, everything works just fine. How do I make this work???
Your error come from the fact you try to access a Database object which has not been initialized yet by getRes().
Because on $(document).ready you were creating a first database with no options, when getRes got trigger you should update its content instead of creating a second Database() on top of the same element (which explain the "Cannot reinitialise DataTable")
Try to move the table var from your document ready to your on event:
$(document).ready(function() {
$('#resdatatable tbody').on('click', 'tr', function () {
var table = $('#resdatatable').DataTable();
var data = table.row( this ).data().id;
Or maybe init the $('#resdatatable tbody').on on getRes() as it might not have access to tbody yet:
getRes(function (result) { // APPLIED CALLBACK
$('#resdatatable').DataTable({
...
});
$('#resdatatable tbody').on('click', 'tr', function () {
...
How I fixed this problem:
I added a 1ms delay for the code to run:
setTimeout(function() {
$(document).ready(function() {
var table = $('#resdatatable').DataTable();
$('#resdatatable tbody').on('click', 'tr', function () {
var data = table.row( this ).data().id;
$.ajax({
type: 'POST',
url: 'getreservationsdetails.php',
dataType: 'json',
data: { id:data, },
success: function(response) {
$('#resulttitle').html("Booking ID # " + response[0].id);
$('#resdetname').html(response[0].name);
$('#resdetbdate').html(response[0].bookingdatetime);
$('#resdetadd').html("<br>" + response[0].address + "<br>" + response[0].city + "<br>" + response[0].state + " " + response[0].post);
$('#resdetphone').html(response[0].phone);
$('#resdetemail').html(response[0].email);
$('#resdetdln').html(response[0].dlnum);
$('#resdetdle').html(response[0].dlexp);
$('#resdetdlc').html(response[0].dlcountry);
$('#resdetpickup').html(response[0].pickuploc + " " + response[0].pickupdatetime);
$('#resdetduration').html(response[0].duration);
$('#resdetdrop').html(response[0].droploc + " " + response[0].dropdatetime);
$('#resdetclass').html(response[0].class);
$('#resdetcoverage').html(response[0].coverage);
$('#resdetage').html(response[0].age);
$('#resdetnumofdrivers').html(response[0].numofdrivers);
$('#resdetroadside').html(response[0].roadsideass);
$('#resdetafterhoursdrop').html(response[0].afterhoursdrop);
$('#resdetpromo').html(response[0].promo);
$('#resdetquote').html(response[0].quote);
$('#resdetaddcomments').html(response[0].name);
$('#resdetip').html(response[0].ip);
$("#modalresult").modal();
}
});

How to cancel pending api call, when dialogBox is closed

I have to upload some files, for each file api is being called. Now if user want to cancel the upload using cancel button in a dialog box.
Please suggest how to reach to this solution.
I am using react and javascript for the file upload.
File upload component is in a different component.
api call is at utils page as shown
_bulkUpload: function(query, rType,sucessCount,failureCount,name) {
Api._callAPI(Url.BULK_UPLOAD, 'POST', query, (type, dt) => {
if(type=="success"){
let data = dt.res_data;
dispatcher.dispatch({
type:'DRAFT_BULK_UPLOAD',
response: sucessCount,
name: name,
});
dispatcher.dispatch({
type:'SNACKBAR',
str: dt.res_str,
toastType:0,
});
/*dispatcher.dispatch({
type:'DRAFT_BULK_UPLOAD',
response: count
});*/
} else {
dispatcher.dispatch({
type:'BULK_FAILED',
response: failureCount,
name: name
});
dispatcher.dispatch({
type: 'SNACKBAR',
str: Api._showErrorMsg(dt.status,dt.responseJSON||'')
});
}
dispatcher.dispatch({
type: 'LOADER',
loader: false
});
}, rType);
},
Api._callAPI function is calling a component as shown.
_callAPI : function(url,method,data,target,cType){
if(data && data.org_id && ([Url.PRELOGIN_CREATE_SUPER_USER,Url.PRELOGIN_CREATE_USER].indexOf(url) !== -1)){
// data.org_id = this._getKey('org_id');
}
else{
if([Url.SSO_CHECK,Url.PRELOGIN_FETCH,Url.LOGIN,Url.PRELOGIN_SEND_OTP,Url.PRELOGIN_VERIFY_OTP,Url.PRELOGIN_VERIFY_EMAIL,Url.COUNTRYCODE_TYPEAHEAD].indexOf(url) === -1)
if(!this._getKey('id') || !this._getKey('value')){
return false;
}
}
$.ajax({
url: BASEURL+url,
method: method,
data: data,
processData: (cType == 'multipart/form-data' ? false :true),
dataType: (cType == 'multipart/form-data' ? '' :'json'),
beforeSend: (xhr) => {
if(this._getKey('id') && this._getKey('value')){
xhr.setRequestHeader('XYZ-ID',this._getKey('id'));
xhr.setRequestHeader('XYZ-VALUE',this._getKey('value'));
if (this._getKey('viewType') == 'Privileged') {
xhr.setRequestHeader('XYZ-HASROLE','Y');
}
else{
xhr.setRequestHeader('XYZ-HASROLE','N');
}
xhr.setRequestHeader('x-csrfvalue',Math.random());
if (this._getKey('delegation_bit') === 'true') {
xhr.setRequestHeader('XYZ-DELEGATOR', this._getKey('delegator_id'));
xhr.setRequestHeader('XYZ-DELEGATION-ID', this._getKey('delegation_id'));
}
}
},
contentType: cType ? false : "application/x-www-form-urlencoded",
success: (data,textStatus, jqXHR) => {
if(jqXHR.getResponseHeader('XYZ-ID')){
this._setKey('id',jqXHR.getResponseHeader('XYZ-ID'));
}
if(jqXHR.getResponseHeader('XYZ-VALUE')){
this._setKey('value',jqXHR.getResponseHeader('XYZ-VALUE'));
}
/*dispatcher.dispatch({
type: 'LOADER',
loader: false
});*/
target('success',data);
},
error: (jqXhr,textStatus,error) => {
dispatcher.dispatch({
type: 'LOADER',
loader: false
});
if(jqXhr.status == 401){
this._clearStorage();
// try {
// sessionStorage.setItem('lastVisitedPage', window.location.hash.split("#")[1].split("?")[0]);
// } catch (ex) {
// console.log("Does not support CRUD with Storage");
// }
this._redirectToLogin();
} else{
target('error',jqXhr,textStatus,error);
}
}
});
},
File Upload and api call part
_handleFileUpload(){
let {failedBillCounter,statusArr} = this.state;
let sucessCount = 0;
let failureCount = 0;
var count=failedBillCounter;
let newFiles = document.getElementById('myFile').files;
let arr = [];
if(newFiles.length > 25){
UserInfoStores.showToast(Errors.MAX_NO_OF_FILE);
document.getElementById('myFile').value = "";
return false;
}
this.setState({fileCount:newFiles.length})
document.getElementById('draftBillBar').style.display = 'block';
//let newData = new FormData();
for(let i=0;i< newFiles.length;i++){
let newData = new FormData();
let files = [];
let txn_attachments = [];
if(newFiles[i].size/(1024*1024) > 15){
count=count+1;
statusArr.push({name:newFiles[i].name,type:'failed'})
this.setState({
statusArr,
failedBillCounter:count,
failCounterFlag:true,
},()=>this.progressBar());
}
else{
newData.append('files-'+i,newFiles[i],newFiles[i].name);
txn_attachments.push('files-'+i);
newData.append('txn_attachments', txn_attachments);
newData.append('source', 'web');
newData.txn_attachments = JSON.stringify(txn_attachments);
DraftAction.draftBulkUpload(newData,'multipart/form-data', sucessCount,failureCount,newFiles[i].name)
}
}
}
you must make a function to cancel the upload make a global variable for your ajaxCall
var ajaxCall;
_callAPI : function(...) {
...
...
ajaxCall = $.ajax({ ... });
}
// make a function to call when user click the cancel upload button
_cancelAjaxCall : function() {
ajaxCall.abort();
}
hope it works...

Show partial view model using Ajax - ASP.NET C# AJAX JQuery

I am looking to show a modal, I have my Modals as partial classes, so if you select the class .js-verify-songs it loads up the partial _VerifySong . If however there is an error, it should load up the error partial _ErrorMessage. And finally if you select .js-reject-song it should load _RejectSong partial.
Any idea how I would do this, please?
to show errors. Currently I have this in my Controller to handle errors:
public partial class SongsManagementController : BaseController
{
private const string NoDataFound = "No data found.";
private const string InvalidDataPosted = "Invalid data posted";
private const string InvalidRequest = "Invalid request.";
private const string VerificationFailedUnexpectedError = "The following song failed to verify due to an unexpected error, please contact RightsApp support.";
private const string ConcurrencyError = "The following song failed to verify as another user has since changed its details.";
[HttpPost]
[Route("VerifyNewSongs")]
[AuthorizeTenancy(Roles = "super,administrator")]
public async Task<ActionResult> VerifyNewSongs(List<VerifySongViewModel> verifySongViewModels)
{
// Not AJAX method - refuse
if (!Request.IsAjaxRequest())
return RedirectToAction("NewSongs", "SongsManagement");
if (verifySongViewModels.NullOrEmpty())
{
// return error;
return Json(new JsonBaseModel
{
success = false,
message = InvalidRequest,
data = null,
errors = new List<string>
{
InvalidDataPosted
}
});
}
foreach (var verifySong in verifySongViewModels)
{
if (verifySong.WorkId == default(Guid) || verifySong.RowVersion == default(Guid))
{
return Json(new JsonBaseModel
{
success = false,
message = InvalidDataPosted,
data = null,
errors = new List<string>
{
$"Invalid data posted for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
var work = await _artistAccountService.GetWorkGraphAsync(verifySong.WorkId, includeWriterAmendments: true);
if (work == default(WorkGraphModels.Work))
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"No data found for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
if (work.VerifiedState != Domain.Enumerators.VerifiedStateType.NotVerified)
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"Song already verified.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
work.RowVersion = verifySong.RowVersion;
var workAndAmendment = new WorkGraphModels.WorkAndAmendment
{
Original = work,
Amendment = null
};
var verifiedState = await _artistAccountService.VerifyWorkGraphAsync(workAndAmendment, GetLoggedUserId());
if (!verifiedState.ValidationErrors.NullOrEmpty())
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else if (!verifiedState.DatabaseErrors.NullOrEmpty())
{
if (!verifiedState.FatalException)
{
// concurrency exception
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
ConcurrencyError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else
{
// fatal
return Json(new JsonBaseModel
{
success = false,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
}
}
return Json(new JsonBaseModel
{
success = true,
message = "All songs verified successfully."
});
}
};
}
This is my Main View:
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_SentricLayout.cshtml";
var actionName = ViewContext.RouteData.Values["Action"].ToString();
#* calc full account code *#
var fullAccountCode = Model.WorkUniqueCode;
ViewBag.Title = "New Songs";
}
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/datetimepicker")
<script language="javascript" type="text/javascript">
#* DOM ready? *#
$(function () {
addTableStylingScripts();
var selectFormDiv = $('.catalogSelector');
selectFormDiv.hide();
$(".records-selected").hide();
// clear all filter boxes and reset search.
$("#btnClear").click(function()
{
$("#newSongsSearch").find(':input').each(function ()
{
if (this.type === "text")
{
$(this).val("");
}
});
$("#btnSearch").click();
});
#* edit catalogue button *#
$('#changeCat').click(function () {
$('#errorContainer').hide();
var label = $('#catLabel');
if (label.is(":visible")) {
label.hide();
selectFormDiv.show();
$('#changeCat').addClass("active");
} else {
label.show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
}
});
#* edit dropdown *#
$("#catalogueSelect").on("change", function () {
#* change display on select change *#
$('#errorContainer').hide();
$('#catLabel').show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
#* set up ajax post to controller *#
var model = {
AccountCode: '#fullAccountCode',
CurrentAccountId: $('#currentAccountId').val(),
CurrentRowVersion: $('#currentRowVersion').val(),
NewCatalogueId: $('#catalogueSelect option:selected').val(),
Action: '#actionName'
};
$.ajax({
url: '#Url.Action("ChangeCatalogue", "ArtistAccount")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
#* ajax worked *#
if (result.ChangeStatus === "Success")
{
var newSelected = $('#catalogueSelect option:selected').text();
$('#catLabel').html(newSelected);
#* update dropdown context *#
var newSelectedId = $('#catalogueSelect option:selected').val();
$('#currentCatalogue').val(newSelectedId);
#* update rowversion *#
var newRowVersion = result.OldOrNewRowVersion;
$('#currentRowVersion').val(newRowVersion);
}
else
{
$('#errorContainer').show();
$('#errorMessage').html(result.ErrorMessage);
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
},
error: function () {
#* failed *#
$('#errorContainer').show();
$('#errorMessage').html('There was a server error, please contact the support desk on (+44) 0207 099 5991.');
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
});
});
function loadPartialPage(url) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: url,
type: 'GET',
cache: false,
success: function (result) {
$('.spinnerOverlay').addClass('hide');
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
}
function getSelectedWorks() {
var selectedWorks = $(".individual:checked");
var works = [];
$.each(selectedWorks, function (key, value) {
works.push(getSelectedWork(this));
});
return works;
}
// verify songs in bulk
$(document).on("click", ".js-verify-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
verifySongs(works);
});
// reject songs in bulk
$(document).on("click", ".js-reject-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
});
function getSelectedWork(element) {
var work = new Object();
work.WorkId = getRowData(element, "id");
work.RowVersion = getRowData(element, "rowversion");
work.UniqueCode = getRowData(element, "uniqueworkid");
work.SongTitle = getRowData(element, "songtitle");
return work;
}
// verify one song
$(document).on("click", ".js-verify-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
verifySongs(works);
});
// reject one song
$(document).on("click", ".js-reject-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
});
function verifySongs(songs) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: '#Url.Action("VerifyNewSongs", "SongsManagement")',
data: JSON.stringify(songs),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('.spinnerOverlay').addClass('hide');
if (result.success) {
loadPartialPage($(".paginate_button.active a").attr("href"));
}
},
error: function(error) {
$('.spinnerOverlay').addClass('hide');
}
});
}
#* Pagination Async Partial Handling *#
$(document).on("click",
"#indexPager a",
function() {
if ($(this).parent().hasClass('disabled') || $(this).parent().hasClass('active'))
return false;
loadPartialPage($(this).attr("href"));
return false;
});
$(document).on("change",
"#pageSizeSelector",
function() {
var selectedValue = $(this).val();
loadPartialPage(selectedValue);
return false;
});
#* Sorting Async Partial Handling *#
$(document).on("click",
"#tableHeader a",
function()
{
loadPartialPage($(this).attr("href"));
return false;
});
});
// Ensure that after paging and sorting ajax calls we re-bind
// the change event and hide the record count label.
$(document).ajaxComplete(function() {
$(".records-selected").hide();
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
});
// Search functions
$('.searchDivider').click(function (e) {
$('#searchFields').slideToggle();
var isSearchShown = $(this).find('.caret').hasClass("caret-up");
if (isSearchShown) {
$(this).children('span').replaceWith('<span class="bg-white">Search <b class="caret"></b></span>');
} else {
$(this).children('span')
.replaceWith('<span class="bg-white">Search <b class="caret caret-up"></b></span>');
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
$(window).resize(function () {
if ($(window).width() >= 1024) {
$('#searchFields').show();
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
// Checks individual checkboxes and displays the count
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
//Disable Top Verify Button if two or more checkboxes are selected.
$('.verify-btn').prop('disabled', true);
//Disable Action Button in the columns when more than one checkbox is selected
$('.table-btn').prop('disabled', false);
$(".individual").on("click", function () {
if ($(".individual:checked").length > 1) {
$('.table-btn').prop('disabled', true);
$('.verify-btn').prop('disabled', false);
}
else {
$('.table-btn').prop('disabled', false);
$('.verify-btn').prop('disabled', true);
}
});
// When one or more works are selected, will enable the top action menu.
// Will disable when none selected.
function determineActionButtonAvailability() {
if ($(".individual:checked").length > 1) {
$(".records-selected").show();
$("#selected").text($(".individual:checked").length);
$("#total").text($(".individual").length);
$(".verify-btn").prop('disabled', false);
if ($(".individual:checked").length > 1) {
}
}
else {
$(".records-selected").hide();
$('.table-btn').prop('disabled', false);
$(".verify-btn").prop('disabled', true);
}
}
// Enforce only numeric input in the Unique Id search textbox.
$(document).on("keydown", ".uniqueCodefield", function (e) {
var key = window.event ? e.keyCode : e.which;
var currentVal = $('.uniqueCodefield').val();
if (key === 8 || key === 9 || key === 13 || key === 37 || key === 39 || key === 35 || key === 36 || key === 46) {
return true;
} else if (key === 13) {
$('#newSongsSearch').validate();
if ($('#newSongsSearch').valid()) {
return true;
}
return false;
}
else if ((key < 48 || key > 57) && (key < 93 || key > 105)) {
return false;
} else if (currentVal.length >= 10) {
return false;
} else {
return true;
}
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
// Only perform the search if the search criteria is valid.
if (!$('#newSongsSearch').valid()) {
return false;
}
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel: {
WorkUniqueCode: $('#SongCode').val(),
SongTitle: $('#SongTitle').val(),
CatalogueUniqueCode: $('#CatalogueCode').val(),
CatalogueName: $('#CatalogueName').val(),
AccountUniqueCode: $('#AccountCode').val(),
AccountName: $('#AccountName').val()
}
};
$.ajax({
url: '#Url.Action("SearchNewSongs", "SongsManagement")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel : {
Name: $('#ContractNameSearch').val(),
ContractType: $('#ContractTypeSearch').val(),
CreatedBy: $('#CreatedBySearch').val(),
DateFrom : $('#DateFromSearch').val(),
DateTo : $('#DateToSearch').val()
}
};
$.ajax({
url: '#Url.Action("SearchContracts", "ClientSetup")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
</script>
#Scripts.Render("~/bundles/searchusers-autosuggest")
}
#section additionalStyles {
#Styles.Render("~/plugins/datatables/media/css/cssDatatables")
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-12">
<div class="panel panel-visible">
#Html.Partial("_NewSongsSearch", Model)
</div>
</div>
<div class="col-md-12">
<div class="panel panel-visible" id="tableContainer">
#Html.Partial("_NewSongsList", Model)
</div>
</div>
</article>
I am unsure though how I would show a list of error in my error partial view. Also how do you load a partial view with Ajax?
Currently you click verify and it loads the spinner, but I would like to load a partial view which is a modal. I’ve used partials because it’s what was decided. I’m just unsure how to get them to load using Ajax.

how to create run time element? where i am doin wrong help....help

new Ajax.Request('Handler.ashx',
{
method: 'get',
onSuccess: function(transport)
{
var response = transport.responseText || "no response text";
//alert("Success! \n\n" + response);
var obj = response.evalJSON(true);
alert(obj[0].Nam);
alert(obj[0].IM);
for(i = 0; i < 4; i++)
{
$('MyDiv').insert( new Element('checkbox', { 'id': "Img" + obj[i].Nam, 'value': obj[i].IM }) );
return ($('MyDiv').innerHTML);
}
},
onFailure: function() { alert('Something went wrong...') }
});
checkbox is not valid tag name. Are you trying to create <input type="checkbox" />?
new Element('input', { type: 'checkbox', ... })
Also, it makes no sense to call return in onSuccess callback function.

Categories

Resources