Problem not displaying success message for each registration with Ajax - 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("");
});

Related

Ajax Request In Order

I'm making litte app to get pages by URL and check their title.
I need check URLs line by line which is user pasted in textarea.
Process sequence :
Check URL > append response to page > then check next url......
Here is my code :
HTML :
<textarea id="textarea" name="urlLine"></textarea>
<button type="button" name="action" id="check">Check IT!</button>
Js :
function getResp(req) {
var uri = req.shift();
$.ajax({
type: 'POST',
url: 'r.php',
async: true,
data: {'uriLine': uri},
success: function (msg) {
$('.collection').append(msg);
$('body').animate({
scrollTop: height,
}, 500)
},
fail: function (msg) {
console.log(msg);
}
});
if (typeof uri !== 'undefined' && uri.length > 0) {
setTimeout(getResp, 5, req);
} else {
alert('Finish');
}
}
$(document).ready(function () {
$('#check').click(function () {
var uris= $('textarea').val().split('\n');
getResp(uris);
});
PHP :
sleep(5); // I don't know why i'm adding. Just wait for performance.
$title = 'title_i_searching';
$adress = $_POST['uriLine'];
if($check->chekURL('https://'.$adress) == $title){
echo ' OK';
}else{
echo 'NOT OK';
}
PHP CLASS :
class checkES
{
public $url;
public function chekURL($url){
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
"http"=>array(
"timeout"=> 5
)
);
$str=
file_get_contents($url,false,stream_context_create($arrContextOptions));
if(strlen($str)>0){
$str = trim(preg_replace('/\s+/', ' ', $str));
preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title);
return $title[1];
}
}
public function parseByLine($content){
$lines = preg_split('/\r\n|[\r\n]/', $content);
return $lines;
}
}
But when i run this code for example; in 20 URL searching on 5th url page alert 'finish'. But append function still continue.
Sometimes, page crash down.
I could not find the healthy method.
I wish i was explain. Sorry for bad language.
Try moving the code to process next uri in success function like this:
function getResp(req) {
var uri = req.shift();
$.ajax({
type: 'POST',
url: 'r.php',
async: true,
data: {'uriLine': uri},
success: function (msg) {
$('.collection').append(msg);
$('body').animate({
scrollTop: height,
}, 500);
if (typeof uri !== 'undefined' && uri.length > 0) {
setTimeout(getResp, 5, req);
} else {
alert('Finish');
}
},
fail: function (msg) {
console.log(msg);
}
});
}

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.

How do I include an Ajax validator before sending

I managed to make this code to submit a form, it works fine, but I can not implement a validator does not need it, but it shows no message just does not send the form is empty.
I searched but could not quite do it. Can anyone help me?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#newsletter').submit(function(){
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "newsletter_cadastrar.asp?f=1",
data: dados,
success: function( data )
{
$('#resultado-form-newsletter').html(data);
}
});
return false;
});
});
</script>
<input id="nomenewslbase" name="nomenewslbase" type="text">
<input id="emailnewslbase" name="emailnewslbase" type="email">
Thank you for your attention.
If you are looking for applying jquery validation rules then you can do it like:
<script type="text/javascript">
function ValidationRules() {
}
ValidationRules.prototype.initializeSaveValidators = function() {
jQuery.validator.addMethod("csProjectName",
function(value, element) {
if ($.trim($('#txtProjectName').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
} else
return true;
}, "Project Name is required");
jQuery.validator.addMethod("csDescription",
function (value, element) {
if ($.trim($('#txtDescription').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
}
else
return true;
}, "Description is required");
};
ValidationRules.prototype.enableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: true };
jQuery.validator.classRuleSettings.csDescription = { csDescription: true };
};
ValidationRules.prototype.disableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: false };
jQuery.validator.classRuleSettings.csDescription = { csDescription: false };
};
jQuery(document).ready(function () {
var validationRules = new ValidationRules();
validationRules.initializeSaveValidators();
validationRules.enableSaveValidators();
$("#btnsubmit").click(function () {
applyjQueryValidation();
return false;
});
});
function applyjQueryValidation() {
var isValid = $('#newsletter').valid();
//here you can manually check for some extra validations
if (isValid==true) {
alert("valid");
//here is you ajax call
}else{
alert("invalid");
}
}
</script>
Also, you need to include jquery.validate.js
Here is the JSfiddle working example.

Backbonejs collection.create: how to prevent it from adding items if there is an error?

How can I prevent collection.create from adding items into its collection if there is an error found in the input?
html,
<div id="new-status">
<h2>New monolog</h2>
<form action="">
<textarea name="content"></textarea><br>
<input type="submit" value="Post">
</form>
</div>
<div id="statuses">
<h2>Monologs</h2>
<ul></ul>
</div>
backbone,
var Status = Backbone.Model.extend({
initialize: function(){
},
validate: function(attrs, options) {
if(attrs.text === '') alert("please enter some text");
},
url:"dummy.php",
sync: function (method, model, options) {
return $.ajax({
type: "POST",
dataType: 'json',
url: 'server.php',
data: {
text: this.get("text")
}
});
}
});
var Statuses = Backbone.Collection.extend({
model: Status
});
var NewStatusView = Backbone.View.extend({
events: {
"submit form": "addStatus"
},
initialize: function(options) {
_.bindAll(this, 'addStatus', 'clearInput');
this.listenTo(this.collection, 'add', this.clearInput) ;
},
addStatus: function(e) {
e.preventDefault();
this.collection.create({ text: this.$('textarea').val() });
},
clearInput: function() {
this.$('textarea').val('');
}
});
var StatusesView = Backbone.View.extend({
initialize: function(options) {
this.collection.on("add", this.appendStatus, this);
},
appendStatus: function(status) {
this.$('ul').append('<li>' + status.escape("text") + '</li>');
}
});
$(document).ready(function() {
var statuses = new Statuses();
new NewStatusView({ el: $('#new-status'), collection: statuses });
new StatusesView({ el: $('#statuses'), collection: statuses });
});
So, when you hit the submit button without typing any text, you get an error popup from this part in the model,
validate: function(attrs, options) {
if(attrs.text === '') alert("please enter some text");
},
But how can I tell the collection that there is an error and do not add this empty item and also do not fire sync in the model?
EDIT:
got it worked with collection.create in this way...
model,
validate: function(attrs, options) {
if(attrs.text === '') {
var message = "please enter some text";
alert(message);
return message;
}
},
view,
addStatus: function(e) {
e.preventDefault();
var one = new Status({ text: this.$('textarea').val() });
if (!one.isValid()) {
alert(one.validationError);
} else {
this.collection.create(one);
}
},
it seems to work fine unless it is not a good approach or against MVC pattern?
I don't think collection.create is the right choice here.
addStatus: function(e) {
e.preventDefault();
var status = new Status({"text": this.$('textarea').val()})
var error = status.valiate();
if(!error) {
this.collection.add(status);
}
},
Also not that the backbone docs says this about validate:
If the attributes are valid, don't return anything from validate; if
they are invalid, return an error of your choosing. It can be as
simple as a string error message to be displayed, or a complete error
object that describes the error programmatically.
So, your validate function should be fixed:
validate: function(attrs, options) {
if(attrs.text === '') {
var message = "please enter some text";
alert(message);
return message;
}
},
Your Model's validate method should return an error string so that models save is not fired in case of alert.
validate: function(attrs, options) {
if(attrs.text === ''){
alert("please enter some text");
return "Text is empty."; // OR proper error CODE
}
}
Check validate method of Backbone.Model.

How to send ajax request to check session timeout and render relogin message in grails?

I want to display a message to the user saying, "you're logged out re-login please!" when session is timed-out, sending an ajax request each time. If session timer ends i want to send final ajax request displaying above message. But the problem here is i don't know where should i have to keep my ajax and jquery codes and since i don't have much knowledge about ajax request, can anyone explain this process with codes. In siple my requirement is like of what facebook shows on session time out, or when any one tab in case of multiople tabs are logged out. I'm working on grails project.
Do your ajax request like this
$.ajax({
url:url,
type:"POST", // or get
data:parameters,
success: function(data) {
// do procedure if success
}
error : function(xhr, type, error){
// do procedure if fail
// may be send a message to the server side to display a message that shows session timeout
}
});
Handle your session timeout in the error function
I did it myself and this is the js code for it "gracefulSession.js" and call this javascript at the page where you are going to embed your html code..
function checkSessionStatus() {
var lStorage = getLocalStorage();
if (lStorage) {
//lStorage.setItem('poleTime',new Date());
var poleTime = lStorage.getItem("poleTime");
var parsedTime;
try {
parsedTime = new Date(poleTime);
} catch (e) {}
//alert(new Date()-parsedTime)
//alert(new Date())
//alert(parsedTime)
//3900000 = 1H5M
if (parsedTime && (new Date() - parsedTime) < 3900000) {
//alert('NCATCH'+parsedTime);
} else {
//alert('POINT');
poleSessionStatus();
}
}
}
function setlatestPoleTIme() {
//alert("SETTING POLE TIME");
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('poleTime', new Date());
}
}
function setCheckSessionTimer() {
var lStorage = getLocalStorage();
var isLoggedOut = false;
if (lStorage) {
if (lStorage.getItem('isLoggedOut') == 'true') {
isLoggedOut = true;
}
}
//console.log('checkingIfLoggedOut');
if (!isLoggedOut) {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("NOPT LO");
$('#LoggedoutMessage').hide();
checkSessionStatus();
} else {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("KO");
//alert("You're Logged Out from other tab");
$('#LoggedoutMessage').show();
}
}
function logout() {
//alert("LOGGIN OUT")
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('isLoggedOut', 'true');
}
}
function resetLoggedOutFLag() {
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.removeItem('isLoggedOut');
}
}
function getLocalStorage() {
var storage, fail, uid;
try {
uid = new Date;
(storage = window.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch (e) {}
return storage
}
Now, HTML code to embed ,
<div id="LoggedoutMessage" style="display:none;position:absolute;background:black;height: 200%;width:100%;top: 0;z-index: 10000;opacity: 0.9;">
<div id="login_box" style="position:fixed;left:38%;top:30%; padding:10px; width: 365px;margin: 0 auto;border: 0px solid #CCC;margin-top: 35px;height: 150px;background: white; border-radius:3px;">
<div id="login_title">
<h1>You have been logged out.</h1>
</div>
<div id="reLogin">
<p>Please login to continue.</p>
<g:link controller="dashBoard" action="index" target="_blank" onclick="logout();">Login</g:link>
</div>
</div>
</div>
Finally where you keep your html,keep this javascript code at top of it embedding script tag:
function poleSessionStatus() {
jQuery.ajax({
type: 'POST',
data: '',
url: '<g:createLink action="ajaxCheckSession" controller="dashBoard"/>',
success: function (data, textStatus) {
//setTimeout ( "checkSession();", 5000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#LoggedoutMessage').show();
},
complete: function (XMLHttpRequest, textStatus) {
$.unblockUI();
}
});
}

Resources