dialog close event jquery mobile not working - events

I am working on jQuery mobile dynamic dialog. Everything is working fine except the close event.
$(document).ready(function () {
$('#btnalert').click(function () {
alert('click');
msg('hello', 'info', function () {
alert('call back function');// this line is not called
});
});
});
function msg(_msg, _title, _okCB) {
try {
if (_title == null || _title == undefined || _title == '') {
_title = 'Information';
}
if (_msg == null || _msg == undefined || _msg == '') {
_msg = 'Error found. Please contact your administrator.';
}
// Create it in memory
var dlg = $("<div id=\"dlgAlert\" class=\"ui-corner-all ui-shadow\" data-close-btn=\"right\" />")
.attr("data-role", "dialog")
.attr("id", "dialog");
var header = $("<div />")
.attr("data-role", "header")
.attr("role", "banner")
.html("<h2>" + _title + "</h2>");
var content = $("<div style=\"padding: 15px;\" />")
.attr("data-role", "content")
.append($("<p />").html(_msg));
content.append("<div ><a class='dlgalert' href='#index' data-rel='back' data-role=\"button\" data-theme=\"c\" >Close</a></div>");
dlg.append(header).trigger('create');
dlg.append(content).trigger('create');
dlg.appendTo($.mobile.pageContainer);
$.mobile.changePage(dlg, {
transition: "pop",
role: "dialog",
reverse: false
});
} catch (e) {
alert(e);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<a id="btnalert" data-role="button"> alert</a>

add below code in your function . check here DEMO
dialogs are simply pages which display dialogs . so here you can call pagehide event.
dlg.on("pagehide",function(){
alert("Dialog closed");
});
or check DEMO
dlg.off("pagehide").on("pagehide",function(){
alert("Dialog closed");
});

Related

Problem not displaying success message for each registration with Ajax

I want to do this after the user registers, shows a successful message and the text boxes are empty again and ready for the next registration, but the registration success message is only displayed for the first registration, but I want to Display each registration
public IActionResult submitSingelControlItem(int Projectid,String calender, String ProjectName,String ProjectManagementName, String ajaxControlItem,String ajaxFraindName,int SingelControlState)
{
Hesabrsee hesabrsee = new Hesabrsee();
hesabrsee.ControlDate = ConvertDateTime.ConvertShamsiToMiladi(calender);
hesabrsee.SabtDate = DateTime.Now;
hesabrsee.Projectid = Projectid;
hesabrsee.ProjectName = ProjectName;
hesabrsee.ProjectManagementName = ProjectManagementName;
hesabrsee.FaraindName = ajaxFraindName;
hesabrsee.Deiscreption = ajaxControlItem;
hesabrsee.ControlState = SingelControlState;
_context.Add(hesabrsee);
_context.SaveChanges();
return Json(new { status = "ok" });
}
<script>
$("#btn").on('click', function () {
var ajaxFraindName = $("#ajaxFraindName").val();
var ajaxControlItem = $("#ajaxControlItem").val();
var calender = $("#calender").val();
var SingelControlState = $("#SingelControlState").val();
if (ajaxFraindName == '' || ajaxControlItem == '' || calender == '' || SingelControlState == '') {
alert("لطفا ورودی ها را پر کنید");
}
else {
$.ajax({
type: "Post",
url: '#Url.Action("submitSingelControlItem", "Hasabrsee")',
data: {
'ajaxControlItem': $("#ajaxControlItem").val(),
'ajaxFraindName': $("#ajaxFraindName").val(),
'Projectid': $("#Projectid").val(),
'ProjectName': $("#ProjectName").val(),
'ProjectManagementName': $("#ProjectManagementName").val(),
'calender': $("#calender").val(),
'SingelControlState': $("#SingelControlState").val(),
}
}).done(function (res) {
if (res.status == 'ok') {
$("#ohsnap").removeClass('d-none').removeClass('alert-danger').addClass('alert-success').html('مورد کنترلی با موفقیت ثبت شد');
$("#ajaxControlItem").val("");
$("#ajaxFraindName").val("");
}
setTimeout(function () {
$('#ohsnap').fadeOut('fast');
}, 2000)
});
}
});
</script>
<div id="ohsnap" class="col-md-4 col-xs-12 alert d-none" style="text-align:center;"></div>
Of course, it displays the message only once because you are removing the class from the $("#ohsnap") div and then you are not restoring it.
Try using Toastr to display the popup alert. It is easier to do.
From the Toastr documentation:
Download the CSS and JS files and add them to your project.
Reference the css <link href="toastr.css" rel="stylesheet"/>
Reference the script <script src="toastr.js"></script>
in your .done() function call toastr;
.done(function (res) {
if (res.status == 'ok') {
toastr.success('title-here', 'مورد کنترلی با موفقیت ثبت شد', {
timeOut: 2000,
closeButton: true,
});
$("#ajaxControlItem").val("");
$("#ajaxFraindName").val("");
});

Summernote custom button with dialog

I want to add a custom button to the Summernote toolbar that opens up a dialog that has a textbox for a URL and several checkboxes for settings. I then want to use the info from the dialog to scrape web pages and do processing on the content. The ultimate goal is to place the scraped content into the editor starting where the cursor is. I've searched and found some code on creating a custom button, but not any solid examples of implementing a dialog. I went through the summernote.js code to see how the Insert Image dialog works and that left me really confused. The test code I've got so far is in the code block, below. Thanks in advance to anyone who can help get me sorted out.
var showModalDialog = function(){
alert("Not Implemented");
};
var AddWiki = function(context) {
var ui = $.summernote.ui;
var button = ui.button({
contents: '<i class="fa fa-plus"/> Add Wiki',
tooltip: "Set a New Wiki",
class: "btn-primary",
click: function() {
showModalDialog();
}
});
return button.render();
};
$(".tw-summernote-instance textarea").summernote({
airMode: false,
dialogsInBody: false,
toolbar: [["mybutton", ["customButton"]]],
buttons: {
customButton: AddWiki
},
callbacks: {
onInit: function(e) {
var o = e.toolbar[0];
jQuery(o)
.find("button:first")
.addClass("btn-primary");
}
}
});
I found a good, simple example of what I wanted to do. Here's the code:
(function(factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function($) {
$.extend($.summernote.plugins, {
'synonym': function(context) {
var self = this;
var ui = $.summernote.ui;
var $editor = context.layoutInfo.editor;
var options = context.options;
context.memo('button.synonym', function() {
return ui.button({
contents: '<i class="fa fa-snowflake-o">',
tooltip: 'Create Synonym',
click: context.createInvokeHandler('synonym.showDialog')
}).render();
});
self.initialize = function() {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group">' +
'<label>Add Synonyms (comma - , - seperated</label>' +
'<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
'</div>'
var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';
self.$dialog = ui.dialog({
title: 'Create Synonym',
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
// You should remove elements on `initialize`.
self.destroy = function() {
self.$dialog.remove();
self.$dialog = null;
};
self.showDialog = function() {
self
.openDialog()
.then(function(data) {
ui.hideDialog(self.$dialog);
context.invoke('editor.restoreRange');
self.insertToEditor(data);
console.log("dialog returned: ", data)
})
.fail(function() {
context.invoke('editor.restoreRange');
});
};
self.openDialog = function() {
return $.Deferred(function(deferred) {
var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
var $synonymInput = self.$dialog.find('#input-synonym')[0];
ui.onDialogShown(self.$dialog, function() {
context.triggerEvent('dialog.shown');
$dialogBtn
.click(function(event) {
event.preventDefault();
deferred.resolve({
synonym: $synonymInput.value
});
});
});
ui.onDialogHidden(self.$dialog, function() {
$dialogBtn.off('click');
if (deferred.state() === 'pending') {
deferred.reject();
}
});
ui.showDialog(self.$dialog);
});
};
this.insertToEditor = function(data) {
console.log("synonym: " + data.synonym)
var dataArr = data.synonym.split(',');
var restArr = dataArr.slice(1);
var $elem = $('<span>', {
'data-function': "addSynonym",
'data-options': '[' + restArr.join(',').trim() + ']',
'html': $('<span>', {
'text': dataArr[0],
'css': {
backgroundColor: 'yellow'
}
})
});
context.invoke('editor.insertNode', $elem[0]);
};
}
});
}));

Call Ajax.ActionLink using Razor syntax on value changed event

I have a View in which i have criteria a Supplier TextBox a LastMonth dropdown and a Months Textbox.
#using JouleBrokerDB.ViewModels;
#model AssignPayReportToDepositViewModel
#{
ViewBag.Title = "View";
}
<link href="#Url.Content("~/Content/kendo/kendo.common-bootstrap.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/kendo/kendo.bootstrap.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/kendo/kendo.dataviz.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/kendo/kendo.dataviz.bootstrap.min.css")" rel="stylesheet" />
<style>
.treediv {
display: inline-block;
vertical-align: top;
width: 440px;
/*height:400px;*/
min-height: 400px;
text-align: left;
margin: 0 2em;
border-radius: 25px;
border: 2px solid #8AC007;
padding: 15px;
overflow: auto;
}
</style>
<div class="row">
<div class="col-md-9 col-md-offset-1">
#using (Html.BeginForm("Show", "AssignPayReportToDeposit", FormMethod.Post, new { id = "AssignToPayReportForm", #class = "form-horizontal" }))
{
<fieldset>
<!-- Form Name -->
<legend>Assign Pay Report to Deposit</legend>
<div class="form-group">
<!-- Supplier -->
<div class="col-sm-4">
#Html.Label("", "Supplier:", new { #class = "control-label", #for = "textinput" })
<div id="suppliers">
#Html.DropDownListFor(x => x.SuppliersList, new SelectList(Model.SuppliersList, "SupplierID", "Name"), new { id = "ddSupplier", #class = "form-control" })
</div>
</div>
<!-- Last Month -->
<div class="col-sm-4">
#Html.Label("", "Last Month:", new { #class = "control-label", #for = "textinput" })
#Html.DropDownListFor(x => x.LastMonthsList, new SelectList(Model.LastMonthsList), new { #id = "ddLastMonth", #class = "form-control" })
</div>
<!-- Months-->
<div class="col-sm-4">
#Html.Label("", "Months:", new { #class = "control-label", #for = "textinput" })
#Html.TextBox("txtMonths", null, new { type = "number", step = 1, min = 1, max = 12, #class = "form-control", required = "required" })
</div>
</div>
</fieldset>
<div class="treediv">
#Html.Label("", "UnAssigned PayReport:", new { #class = "control-label", #for = "textinput" })
<div id="TreeView_UPR" style="padding:5px"></div>
</div>
<div class="treediv">
#Html.Label("", "Deposits:", new { #class = "control-label", #for = "textinput" })
<h4></h4>
<div id="TreeView_AD" style="padding:5px"></div>
</div>
}
</div>
</div>
<script src="#Url.Content("~/Scripts/kendo/kendo.all.min.js")"></script>
<script src="#Url.Content("~/Scripts/Views/AssignPayReportToDeposit/Show.js")"></script>
Here on this text box i have attached changed event though jQuery. The requirement is that whenever the criteria changes the treeview div will be filled with data will be refreshed.
AssignPayReportsToDeposit.AttachEvents = function () {
$("#ddSupplier").change(AssignPayReportsToDeposit.OnSupplierChange);
$("#ddLastMonth").change(AssignPayReportsToDeposit.OnLastMonthChange);
$("#txtMonths").change(AssignPayReportsToDeposit.OnMonthsChange);
}
these changed event handler will handle the refreshing the treeview. The whole thing is handled through ajax calls.
Now i know that using Ajax.ActionLink and UpdateTargetId parameter with Replace option i can return the treeview in partial view so the manual handling can be removed. but that will require me put the anchor button which user have to click. Requirement is that the refresh of treeview should be done on any criteria change.
Is there any way i am able to achieve this using Ajax.ActionLink (or any another razor syntax that will take load off from the manual handling ) ? On change event of the controls i would like to call a controller using ajax.actionlink which will return a partialview and update the div.
Edit: I am handling this through jQuery right now. so i will post the complete code for more understanding.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JouleBrokerDB;
using JouleBrokerDB.ViewModels;
using JouleBroker.Filters;
namespace JouleBroker.Controllers
{
[RoutePrefix("AssignPayReportToDeposit")]
[Route("{action=Show}")]
public class AssignPayReportToDepositController : Controller
{
// GET: AssignPayReportToDeposit
//[Route("Show",Name = "APTDShow")]
//[ValidateLogin]
public ActionResult Show()
{
List<SupplierViewModel> suppliers = DBCommon.GetAllSuppliers(false);
SuppliersList_LastMonthsList_ViewModel model = new SuppliersList_LastMonthsList_ViewModel()
{
SuppliersList = suppliers,
LastMonthsList = new List<string>()
};
return View(model);
}
[HttpPost]
[Route("GetUnAssignedPayReports")]
public JsonResult GetUnAssignedPayReports(int SupplierID,
string MonthPaid,
int Months)
{
var payreports = AssignPayReportsToDepositData.GetUnAssignedPayReports(SupplierID,
MonthPaid,
Months);
return Json(payreports);
}
[HttpPost]
[Route("GetAssignedPayReports")]
public JsonResult GetAssignedPayReports(int SupplierID,
string MonthPaid,
int Months)
{
var payreports = AssignPayReportsToDepositData.GetAssignedPayReports(SupplierID,
MonthPaid,
Months);
return Json(payreports);
}
[HttpPost]
[Route("AssignDepositIdToPayReport")]
public bool AssignDepositIdToPayReport(int PayReportID, int DepositID)
{
return AssignPayReportsToDepositData.AssignDepositIdToPayReport(PayReportID, DepositID);
}
}
}
JavaScript File (the code is a bit lengthy so you don't need to look at all of them you can see the methods which are calling the action methods. GetUnAssignedPayReports and GetAssignedPayReports which returns the data which is used to fill the tree view.) I just want this portion to moved to partial view and passing model to partial view generate treeview there and replace the div each time on change event with rendering partial view again. Hope i am clear enough. so change the above methods to return partial instead of json result that what i am trying to achive
function AssignPayReportsToDeposit() { }
AssignPayReportsToDeposit.SelectedSupplierID = 0;
AssignPayReportsToDeposit.SelectedLastMonth = null;
AssignPayReportsToDeposit.SelectedMonths = 0;
AssignPayReportsToDeposit.LastMonthsList = null;
AssignPayReportsToDeposit.UnAssignedPayReportsList = null;
AssignPayReportsToDeposit.AssignedPayReportsList = null;
AssignPayReportsToDeposit.LastTextChangedNode = null;
//--------- Document Ready Function -------- //
$(document).ready(function () {
//AttachEvents
AssignPayReportsToDeposit.AttachEvents();
});
AssignPayReportsToDeposit.AttachEvents = function () {
$("#ddSupplier").change(AssignPayReportsToDeposit.OnSupplierChange);
$("#ddLastMonth").change(AssignPayReportsToDeposit.OnLastMonthChange);
$("#txtMonths").change(AssignPayReportsToDeposit.OnMonthsChange);
}
//Handles Supplier ChangeEvents
AssignPayReportsToDeposit.OnSupplierChange = function () {
//Get Changed Supplier ID
AssignPayReportsToDeposit.SelectedSupplierID = $('#ddSupplier').val();
//Get Last Month List
AssignPayReportsToDeposit.LastMonthsList = CommonAction.GetLastPayReportMonthsBySupplierID(AssignPayReportsToDeposit.SelectedSupplierID);
//Fill Last Month List
AssignPayReportsToDeposit.FillLastMonths();
//Refresh TreeView_UPR
AssignPayReportsToDeposit.RefreshTreeViewUPR();
//Refresh TreeView_AD
AssignPayReportsToDeposit.RefreshTreeViewAD();
}
//Handles Last Month Change Event
AssignPayReportsToDeposit.OnLastMonthChange = function () {
AssignPayReportsToDeposit.SelectedLastMonth = $('#ddLastMonth').val();
//Refresh TreeView_UPR
AssignPayReportsToDeposit.RefreshTreeViewUPR();
//Refresh TreeView_AD
AssignPayReportsToDeposit.RefreshTreeViewAD();
}
//Handles Month Change Event
AssignPayReportsToDeposit.OnMonthsChange = function () {
AssignPayReportsToDeposit.SelectedMonths = $('#txtMonths').val();
//Refresh TreeView_UPR
AssignPayReportsToDeposit.RefreshTreeViewUPR();
//Refresh TreeView_AD
AssignPayReportsToDeposit.RefreshTreeViewAD();
}
//Fills Last Month Dropdown with options
AssignPayReportsToDeposit.FillLastMonths = function () {
var ddLastMonth = $("#ddLastMonth");
if (ddLastMonth != undefined) {
ddLastMonth.empty();
if (AssignPayReportsToDeposit.LastMonthsList != undefined) {
$.each(AssignPayReportsToDeposit.LastMonthsList, function () {
Common.AddOptionToSelect(ddLastMonth, this.Text, this.Text);
});
ddLastMonth.val(AssignPayReportsToDeposit.LastMonthsList[0].Text);
AssignPayReportsToDeposit.SelectedLastMonth = ddLastMonth.val();
}
}
}
AssignPayReportsToDeposit.ValidateControls = function () {
var success = true;
if (AssignPayReportsToDeposit.SelectedSupplierID == undefined ||
AssignPayReportsToDeposit.SelectedSupplierID == 0) {
// bootbox.alert('Please select a Supplier');
success = false;
}
else if (AssignPayReportsToDeposit.SelectedLastMonth == undefined ||
AssignPayReportsToDeposit.SelectedLastMonth == '') {
// bootbox.alert('Please select Last Month');
success = false;
}
else if (AssignPayReportsToDeposit.SelectedMonths == undefined ||
AssignPayReportsToDeposit.SelectedMonths == 0) {
// bootbox.alert('Please Enter Months');
success = false;
}
return success;
}
//Assigns DepositIdToPayReport
AssignPayReportsToDeposit.AssignDepositIdToPayReport = function (PayReportID, DepositID) {
var success = false;
if (PayReportID != undefined && DepositID != undefined) {
var jsonData = JSON.stringify({ PayReportID: PayReportID, DepositID: DepositID });
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'AssignPayReportToDeposit/AssignDepositIdToPayReport',
data: jsonData,
async: false,
success: function (result) {
success = result;
},
error: Common.AjaxErrorHandler
});
}
return success;
}
//--------- Tree View UPR Functions -------- //
//Gets UnAssigned Pay Reports
AssignPayReportsToDeposit.GetUnAssignedPayReports = function () {
var payReports;
if (AssignPayReportsToDeposit.ValidateControls()) {
var jsonData = JSON.stringify(
{
SupplierID: AssignPayReportsToDeposit.SelectedSupplierID,
MonthPaid: AssignPayReportsToDeposit.SelectedLastMonth,
Months: AssignPayReportsToDeposit.SelectedMonths
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AssignPayReportToDeposit/GetUnAssignedPayReports",
data: jsonData,
async: false,
success: function (data) {
if (data != undefined && data != "")
payReports = data;
},
error: Common.AjaxErrorHandler
});
}
return payReports;
}
AssignPayReportsToDeposit.BindTreeViewUPR = function () {
var treeview = $("#TreeView_UPR");
var inline = new kendo.data.HierarchicalDataSource({
data: AssignPayReportsToDeposit.UnAssignedPayReportsList,
schema: {
model: {
id: "PayReportID"
}
}
});
treeview.kendoTreeView({
dragAndDrop: true,
dataSource: inline,
dataBound: function (e) {
if (!this.dataSource.data().length) {
this.element.append("<p class='no-items'>No items yet.</p>");
} else {
this.element.find(".no-items").remove();
}
},
dataTextField: ["DisplayValue"],
drop: AssignPayReportsToDeposit.OnTreeViewUPRDrop
});
}
AssignPayReportsToDeposit.OnTreeViewUPRDrop = function (e) {
var isTargetTreeViewAD = false;
var sourceDataItem = this.dataItem(e.sourceNode);
var targetDataItem = this.dataItem(e.destinationNode);
if (targetDataItem == undefined) {
targetDataItem = $("#TreeView_AD").data("kendoTreeView").dataItem(e.destinationNode);
isTargetTreeViewAD = true;
}
if (sourceDataItem == undefined ||
targetDataItem == undefined) {
//Source and target both must exists
e.preventDefault();
return;
}
if (sourceDataItem.IsDeposit == true) {
//Deposits cannot be drag and Drop
e.preventDefault();
return;
}
if (isTargetTreeViewAD) {
if (e.dropPosition == "over" &&
sourceDataItem.IsPayReport == true &&
sourceDataItem.IsAssignedPayReport == false &&
targetDataItem.IsDeposit == true) {
//Source must UnAssigned Payreport Target Must be Deposit and Drop position must over
//Implement logic to assign deposit id to the Pay Report
var PayReportID = sourceDataItem.PayReportID;
var DepositID = targetDataItem.DepositID;
if (AssignPayReportsToDeposit.AssignDepositIdToPayReport(PayReportID, DepositID)) {
sourceDataItem.set("DepositID", DepositID);
sourceDataItem.set("IsAssignedPayReport", true);
}
else {
//Didnt update the record don't do the drop
e.preventDefault();
return;
}
}
else {
e.preventDefault();
return;
}
}
else {
if ((e.dropPosition == "before" || e.dropPosition == "after") &&
sourceDataItem.IsPayReport == true &&
targetDataItem.IsPayReport == true &&
targetDataItem.IsAssignedPayReport == false) {
//Only allow sorting in this condition otherwise cancel drop event
//Means only allow sorting of unassigned payreports within the tree
}
else {
e.preventDefault();
return;
}
}
}
AssignPayReportsToDeposit.RefreshTreeViewUPR = function () {
//Destroy and empty tree
var treeview = $("#TreeView_UPR").data("kendoTreeView");
if (treeview != undefined) { treeview.destroy(); }
treeview = $("#TreeView_UPR");
treeview.empty();
AssignPayReportsToDeposit.UnAssignedPayReportsList = AssignPayReportsToDeposit.GetUnAssignedPayReports();
AssignPayReportsToDeposit.BindTreeViewUPR();
}
//--------- TreeView_AD Functions -------- //
//Gets Assigned Pay Reports
AssignPayReportsToDeposit.GetAssignedPayReports = function () {
var payReports;
if (AssignPayReportsToDeposit.ValidateControls()) {
var jsonData = JSON.stringify(
{
SupplierID: AssignPayReportsToDeposit.SelectedSupplierID,
MonthPaid: AssignPayReportsToDeposit.SelectedLastMonth,
Months: AssignPayReportsToDeposit.SelectedMonths
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AssignPayReportToDeposit/GetAssignedPayReports",
data: jsonData,
async: false,
success: function (data) {
if (data != undefined && data != "")
payReports = data;
},
error: Common.AjaxErrorHandler
});
}
return payReports;
}
AssignPayReportsToDeposit.BindTreeViewAD = function () {
var treeview = $("#TreeView_AD");
var inline = new kendo.data.HierarchicalDataSource({
data: AssignPayReportsToDeposit.AssignedPayReportsList,
schema: {
model: {
id: "DepositID",
hasChildren: "HasAnyAssignedPayReports",
children: "AssignedPayReports"
}
}
});
treeview.kendoTreeView({
dragAndDrop: true,
dataSource: inline,
dataBound: function (e) {
if (!this.dataSource.data().length) {
this.element.append("<p class='no-items'>No items yet.</p>");
} else {
this.element.find(".no-items").remove();
}
},
dataTextField: ["DisplayValue", "DisplayValue"],
drop: AssignPayReportsToDeposit.OnTreeViewADDrop,
select: AssignPayReportsToDeposit.OnTreeViewADSelect
});
}
AssignPayReportsToDeposit.OnTreeViewADSelect = function (e) {
var dataItem = this.dataItem(e.node);
var treeview = this;
if (AssignPayReportsToDeposit.LastTextChangedNode != undefined) {
//Restore last node's Text
var previousDataItem = this.dataItem(AssignPayReportsToDeposit.LastTextChangedNode);
if (previousDataItem != undefined) {
var date = AssignPayReportsToDeposit.FormatDepositMonthToDisplay(previousDataItem.DepositDate);
var displaytext = "[" + date + "]" + "-[" + previousDataItem.BankName + "]-" + "[" + previousDataItem.Amount + "]";
this.text(AssignPayReportsToDeposit.LastTextChangedNode, displaytext);
}
AssignPayReportsToDeposit.LastTextChangedNode = undefined;
}
if (dataItem.IsDeposit) {
if (dataItem.hasChildren > 0) {
dataItem.set("expanded", true);
//Append sum to selected node's diplay value
var childs = dataItem.children.data();
var sum = 0;
$.each(childs, function () { sum += this.Amount });
var date = AssignPayReportsToDeposit.FormatDepositMonthToDisplay(dataItem.DepositDate);
var displaytext = "[" + date + "]" + "-[" + dataItem.BankName + "]-" + "[" + dataItem.Amount + "(" + sum + ")" + "]";
this.text(e.node, displaytext)
AssignPayReportsToDeposit.LastTextChangedNode = e.node;
}
}
}
AssignPayReportsToDeposit.FormatDepositMonthToDisplay = function (jsondate) {
var depositedate = "";
if (jsondate != undefined && jsondate != "") {
var date = Common.ParseDate(jsondate);
var month = ("0" + (date.getMonth() + 1)).slice(-2);
depositedate = date.getFullYear() + "-" + (month);
}
return depositedate;
}
AssignPayReportsToDeposit.OnTreeViewADDrop = function (e) {
var isTargetTreeViewURP = false;
var DroptoNoItemZone = false;
var sourceDataItem = this.dataItem(e.sourceNode);
var targetDataItem = this.dataItem(e.destinationNode);
var treeview_UPR = $("#TreeView_UPR").data("kendoTreeView");
if (targetDataItem == undefined) {
targetDataItem = treeview_UPR.dataItem(e.destinationNode);
if (treeview_UPR.element.find(".no-items").length > 0) DroptoNoItemZone = true;
isTargetTreeViewURP = true;
}
if ((sourceDataItem == undefined ||
targetDataItem == undefined) && DroptoNoItemZone == false) {
e.preventDefault();
return;
}
if (sourceDataItem.IsDeposit == true) {
//Deposits can not be moved within the tree view
e.preventDefault();
return;
}
if (isTargetTreeViewURP) {
if (((e.dropPosition == "before" || e.dropPosition == "after") &&
sourceDataItem.IsPayReport == true &&
sourceDataItem.IsAssignedPayReport == true &&
targetDataItem.IsPayReport == true) || (e.dropPosition == "over" && DroptoNoItemZone)) {
//Implement logic to unassing deposit id to PayReport
var PayReportID = sourceDataItem.PayReportID;
var DepositID = 0;
if (AssignPayReportsToDeposit.AssignDepositIdToPayReport(PayReportID, DepositID)) {
sourceDataItem.set("DepositID", DepositID);
sourceDataItem.set("IsAssignedPayReport", false);
}
else {
//Didnt update the record don't do the drop
e.preventDefault();
return;
}
}
else {
e.preventDefault();
return;
}
}
else {
if (e.dropPosition == "over" &&
sourceDataItem.IsPayReport == true &&
targetDataItem.IsDeposit == true) {
//Implement Logic to change deposit ID for assigned payreport
var PayReportID = sourceDataItem.PayReportID;
var DepositID = targetDataItem.DepositID;
if (AssignPayReportsToDeposit.AssignDepositIdToPayReport(PayReportID, DepositID)) {
sourceDataItem.set("DepositID", DepositID);
sourceDataItem.set("IsAssignedPayReport", true);
}
else {
//Didnt update the record don't do the drop
e.preventDefault();
return;
}
}
else {
e.preventDefault();
return;
}
}
}
AssignPayReportsToDeposit.RefreshTreeViewAD = function () {
//Destroy and empty tree
var treeview = $("#TreeView_AD").data("kendoTreeView");
if (treeview != undefined) { treeview.destroy(); }
treeview = $("#TreeView_AD");
treeview.empty();
AssignPayReportsToDeposit.LastTextChangedNode = undefined;
AssignPayReportsToDeposit.AssignedPayReportsList = AssignPayReportsToDeposit.GetAssignedPayReports();
AssignPayReportsToDeposit.BindTreeViewAD();
}
Unfortunately not out the box.
The Ajax extension methods are really just HTML helpers that work with other jQuery libraries. The helpers create the relavant HTML markup (such as adding custom addtributes data-*="") and the client scripts use this to determine their behaviour.
You could create your own MVC HTML helper and script library to handle change events for you however I would recommend looking at a front end framework such as Angular instead. This library would handle all the events declaratively so you don't need to waste time writing event handlers.

ajaxfileupload problemajaxFileUpload is not a function

I am using ajaxfileupload to upload file , whenever i upload the file it gives me this error . I tried alot to fix it but no luck .
TypeError: $.ajaxFileUpload is not a function
success: function (data, status)
Here is code my code .
$id =$("#id").val();
$.ajaxFileUpload
(
{
type: "POST",
url: "main_page/save_image_data",
secureuri:false,
fileElementId:'userfile'+id,
dataType: 'json',
data: { "image_id":id},
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
/*error: function (data, status, e)
{
alert(e);
}*/
}
)
return false;
There is no command $.ajaxFileUpload in the core of jQuery.
So you are probably trying to use an external library and you have not included it in your <head> .
This can be happened if you have include jquery.min.js inside your page.After remove that file problem will be solved.
add this to your file. this method is removed form upper version of jquery.
jQuery.extend({
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error )
s.error( xhr, status, e );
// If we have some XML response text (e.g. from an AJAX call) then log it in the console
else if(xhr.responseText)
console.log(xhr.responseText);
}
});
this is my solution-----Follow the format of the official:
<script type="text/javascript">
$(document).ready(function() {
var interval;
function applyAjaxFileUpload(element) {
$(element).AjaxFileUpload({
action: "MyJsp.jsp",
onChange: function(filename) {
// Create a span element to notify the user of an upload in progress
var $span = $("<span />")
.attr("class", $(this).attr("id"))
.text("Uploading")
.insertAfter($(this));
$(this).remove();
interval = window.setInterval(function() {
var text = $span.text();
if (text.length < 13) {
$span.text(text + ".");
} else {
$span.text("Uploading");
}
}, 200);
},
onSubmit: function(filename) {
// Return false here to cancel the upload
/*var $fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
$("span." + $(this).attr("id")).replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
return false;*/
// Return key-value pair to be sent along with the file
return true;
},
onComplete: function(filename, response) {
window.clearInterval(interval);
var $span = $("span." + $(this).attr("id")).text(filename + " "),
$fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
if (typeof(response.error) === "string") {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
alert(response.error);
return;
}
$("<a />")
.attr("href", "#")
.text("x")
.bind("click", function(e) {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
})
.appendTo($span);
}
});
}
applyAjaxFileUpload("#demo1");
});
</script>
at least ,no more this error. And the action will receive the request

PhantomJS: event handler that executes AJAX call

This is a simple test case for PhantomJS to demonstrate that an event handler that, when invoked, executes an AJAX call, does not work.
I've created a simple test here to try and access some content loaded via AJAX. It's very possible I've done something wrong, in which case I'd appreciate someone pointing out what that is. However, if not, I think there is a problem with PhantomJS.
Here's a simple page with a single that has a change event bound to it. When the value of the changes, it loads some content from the server and replaces the content of a specific <p>
The text of the <p id="bar">foo</p> should change to 'bar' after the ajax call is completed and processed.
Can anyone help me out?
<html>
<head>
<title>AJAX test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(function(){
$('#getBar').change(function() {
$('#bar').load("/test/bar");
});
});
</script>
</head>
<body>
<h1>Foo</h1>
<div>
<select id="getBar">
<option value=""></option>
<option value="go" id="go">Get Bar Text</option>
</select>
</div>
<p id="bar">foo</p>
</body>
</html>
Here's the script I use to navigate to this simple page and ATTEMPT to use jQuery to change the value of the and trigger the change event.
The steps of the script are broken out into an array of 'step' functions:
var wp = require("webpage");
var system = require('system');
var util = require('./util-module.js'); // my logging API
var baseUrl = 'http://127.0.0.1:8080';
/* Global error handler for phantom */
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line);
});
}
util.log.error(msgStack.join('\n'));
// exit phantom on error
phantom.exit();
};
/* Inject jQuery into the phantom context */
var injected = phantom.injectJs('./jquery.min.js');
util.log.debug('phantom injected jQuery: ' + injected);
/* Create and initialize the page */
var page = wp.create();
var loadInProgress = false;
page.onLoadStarted = function() {
loadInProgress = true;
util.log.debug("page load started: " + page.url);
};
page.onLoadFinished = function() {
loadInProgress = false;
util.log.debug("page load finished: " + page.url);
// inject jquery onto the page
var injected = page.injectJs('./jquery.min.js');
util.log.debug('page injected jQuery: ' + injected);
page.evaluate(function() {
jQuery.noConflict();
});
};
page.onResourceRequested = function(request) {
console.log('Request (#' + request.id + '): ' + JSON.stringify(request));
};
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};
/* Redirect all console messages logged on page to debug */
page.onConsoleMessage = function(msg) {
util.log.debug(msg);
};
var steps = [
function() {
util.log.debug('LOAD THE TEST PAGE');
page.open(baseUrl + "/test/foo");
},
function() {
util.log.debug('CHANGE THE SELECT');
// see what the first result is. change the sort. Wait for the ajax update to complete
// start iterating over results.
var oldTitle = page.evaluate(function() {
return jQuery('#bar').text();
});
util.log.debug('OLD TEXT: ' + oldTitle);
page.evaluate(function(){
jQuery('select').val('go');
jQuery('select').trigger('change');
jQuery('select').change();
console.log('SELECT VALUE AFTER UDPATE: ' + jQuery('select').val());
});
loadInProgress = true;
count = 0;
var fint = setInterval(function() {
var newTitle = page.evaluate(function() {
return jQuery('#bar').text();
});
util.log.debug('NEW TEXT: ' + newTitle);
count++;
if (oldTitle != newTitle) {
clearInterval(fint);
loadInProgress = false;
}
if (count > 5) {
clearInterval(fint);
loadInProgress = false;
}
}, 500);
},
function() {
util.log.debug('PRINT PAGE TITLE');
page.evaluate(function(){
console.log(document.title);
});
},
];
// harness that executes each step of the scraper
var testIndex = 0;
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testIndex] == "function") {
util.log.debug("step " + (testIndex + 1));
steps[testIndex]();
testIndex++;
}
if (typeof steps[testIndex] != "function") {
util.log.debug("test complete!");
clearInterval(interval);
phantom.exit();
}
}, 500);
And here is the output. I'm expecting the text to change from 'foo' to 'bar' but it never happens
DEBUG: CHANGE THE SELECT
DEBUG: OLD TEXT: foo
DEBUG: SELECT VALUE AFTER UDPATE: go
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: step 5
DEBUG: PRINT PAGE TITLE
DEBUG: AJAX test
DEBUG: test complete!
BTW, PhantomJS 1.7. This is a great project.
The problem with the example listed above is that I simply injected jQuery into a page that already had jQuery. When I stopped doing that, it worked.

Resources