how to validate serialized data in Ajax - javascript

I have this particular problem, where I need to validate the data before it is saved via an ajax call. save_ass_rub function is called when user navigates to a different URL.
In my application, I have a custom Window and user is allowed to input data. I am able to capture all the data in this step: var data = $('form').serialize(true);. But I need to loop through this and check if data for some specific elements is empty or not. I can't do it when the user is in the custom window. The Custom window is optional for the user. All I want is to alert the user in case he has left the elements blank before the data is submitted.
We are using Prototype.js and ajax .
<script>
function save_ass_rub() {
var url = 'xxxx';
var data = $('form').serialize(true);
var result;
new Ajax.Request( url, {
method: 'post',
parameters: data,
asynchronous: false, // suspends JS until request done
onSuccess: function (response) {
var responseText = response.responseText || '';
if (responseText.length > 0) {
result = eval('(' + responseText + ')');
}
}
});
if (result && result.success) {
return;
}
else {
var error = 'Your_changes_could_not_be_saved_period';
if (window.opener) { // ie undocked
//Show alert in the main window
window.opener.alert(error);
return;
}
return error;
}
}
// Set up auto save of rubric when window is closed
Event.observe(window, 'unload', function() {
return save_ass_rub();
});
</script>
Can some thing like this be done?
After Line
var data = $('form').serialize(true);
var split_data = data.split("&");
for (i = 0; i < split_data.length; i++) {
var elem = split_data[i];
var split_elem = elem.split('=');
if( split_elem[0].search(/key/) && split_elem[0] == '' ){
console.log( split_elem );
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
}

Instead of using the serialized form string, I would use the form itself to do the validation. if $('form') is your form element then create a separate function that checks the form element so its compartmentalized.
function checkform(form)
{
var emptytexts = form.down('input[type="text"]').filter(function(input){
if(input.value.length == 0)
{
return true;
}
});
if(emptytexts.length > 0)
{
return false;
}
return true;
}
and in the save_ass_rub() function
//..snip
if(checkform($('form') == false)
{
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
var data = $('form').serialize(true);
var result;
I only added text inputs in the checkform() function you can the rest of the input types and any other weird handling you would like to that function. As long as it returns false the error will be displayed and the js will stop otherwise it will continue

Related

Save changes function not properly updating the database

So, I have a button that triggers a javascript function, that calls an AJAX request, that calls an actionresult that should update my database.
Javascript Call
function changeDepartment() {
// Initiate and value variables,
var id = $('#requestId').val();
var user = $('#contactUser').val();
// Bind variables to data object
var data = { id: id }
// Ajax call with data.
$.ajax({
url: '#Url.Action("changeDepartmentActionResult", "ManageRequestResearch")',
type: "POST",
dataType: 'json',
data: data,
success: function (data, textStatus, XmlHttpRequest) {
var name = data.name;
window.location.href = '#Url.Action("Index", "ManageRequestResearch")';
$('#btn-input').val('');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("responseText: " + jqXHR.responseText);
}
});
alert(data);
And then, I have the action result:
[HttpPost]
public ActionResult changeDepartmentActionResult(string id)
{
var moadEntities = new MOADEntities();
moadEntities.Configuration.AutoDetectChangesEnabled = false;
var researchBusiness = new ResearchRequestBusiness(moadEntities);
var request = researchBusiness.FetchRequestById(Convert.ToInt32(id));
var directoryObject = GetActiveDirectoryObject(request.Requestor);
var requstorDisplayName = directoryObject != null ? directoryObject.DisplayName : request.RequestorFullName;
var researchRequestFileBusiness = new ResearchRequestFilesBusiness(moadEntities);
var requestFiles = researchRequestFileBusiness.FetchFilesByRequestId(Convert.ToInt32(id));
var viewModel = new ManageSelectedRequestResearchViewModel()
{
RequestDetails = request,
RequestActivity = request.tbl_ResearchRequestActivity.Select(d => d).ToList(),
Files = requestFiles
};
moadEntities.Configuration.AutoDetectChangesEnabled = false;
if (request.GovernmentEnrollment == true)
{
request.GovernmentEnrollment = false;
request.ManagedCare = true;
moadEntities.SaveChanges();
}
else
{
request.ManagedCare = false;
request.GovernmentEnrollment = true;
moadEntities.SaveChanges();
}
return Json("Status changed successfully", JsonRequestBehavior.AllowGet);
}
From what I have observed, it returns the right record, it makes the changes properly, and it hits the Context.SaveChanges();
when debugging -- i can see before the save changes is made that the values have indeed changed, however--inside the database, no changes are saved.
In addition, i have checked to see that the connection strings are valid.
Any idea what may be causing this?
Thanks ahead of time!
It seems that you are modifying an entity while auto detecting changes are disabled.
If it is intentional then you should inform the context that the entity has been changed.
I assume that MOADEntities is derived from DbContext. So instead of this:
if (request.GovernmentEnrollment == true)
{
request.GovernmentEnrollment = false;
request.ManagedCare = true;
moadEntities.SaveChanges();
}
else
{
request.ManagedCare = false;
request.GovernmentEnrollment = true;
moadEntities.SaveChanges();
}
I would try this:
// Simplify the if..else block
request.ManagedCare = request.GovernmentEnrollment;
request.GovernmentEnrollment = !request.GovernmentEnrollment;
// Notifying the context that the 'request' entity has been modified.
// EntityState enum is under System.Data.Entity namespace
moadEntities.Entry(request).State = EntityState.Modified;
// Now we can save the changes.
moadEntities.SaveChanges();

How to Execute ajax call after the scroller reaches the bottom

I'm correcting working on lazy loading for 200 array of objects and APIs are provided to me to extract JSON from the server (by passing index, row count as parameter for the get AJAX and on response I get the data and the Boolean of whether there are more rows or not). But the problem is that initially I was able to get the data of 10 from the 200 but while I set the scroll function on the div it displays duplicate data which are already appended on the div. Stucked in this problem for a day.
Hope you guys shed some light on me.
var listgen = (function() {
var mc = {};
mc.startindex = 1;
mc.rowcount = 10;
mc.hasmorerows = false;
mc.entity = "requests"
//Declared variables:
mc.initComponent = function() {
var entity = "requests";
mc.callAjaxForList(mc.entity, mc.startindex, mc.rowcount);
$("#reqbody").on('scroll', function() {
if (mc.hasmorerows && ($(this)[0].scrollHeight <= $(this).scrollTop() + $(this).innerHeight())) {
console.log('reached')
mc.callAjaxForList(mc.entity, mc.startindex, mc.rowcount);
}
console.log("scroll");
})
}
mc.callAjaxForList = function(entity, startindex, rowcount) {
var options = {
"list_info": {
"row_count": rowcount,
"start_index": startindex
}
}
$("#reqbody").addClass("loading");
$.ajax({
url: "/data/" + entity,
data: {
"input_data": JSON.stringify(options)
},
contentType: "application/json; charset=utf8",
type: "GET",
success: function(json) {
mc.hasmorerows = json.list_info.has_more_rows
mc.onDataLoading(json);
},
});
}
mc.onDataLoading = function(json) {
//this is where i append the data from the json
mc.startindex += mc.rowcount
}
return mc;
})()
listgen.initComponent();
Scroll is a very high-frequent event, so I think that you have several ajax calls with same data before actually your onDataLoading called, and range incremented. So I whould add mutex.
// ...
mc.loaging = false; // mutex
$("#reqbody").on('scroll', function(){
if(mc.hasmorerows && ($(this)[0].scrollHeight<=$(this).scrollTop()+$(this).innerHeight())){
console.log('reached')
if (!mc.loading) // add check here
mc.callAjaxForList(mc.entity,mc.startindex,mc.rowcount);
}
console.log("scroll");
})
}
mc.callAjaxForList= function(entity,startindex,rowcount){
// ...
mc.loading = true;
$.ajax({
// ...
success:function(json){
mc.hasmorerows=json.list_info.has_more_rows
mc.onDataLoading(json) ;
mc.loading = false;
},
error: ()=> mc.loading = false
});
}
So our mc.loading will tell us if ajax already completed (do not forget to reset it's value on ajax error)

Confirm dialog causes IE to crash

I've got a web app using ASP.NET with C# code behind using JQuery 11.1.2. I have a dropdownlist that is populated by an AJAX call to the server when it is clicked. The web method returns a list of options to include in the dropdown based on args. Some of the options return a 'confirm' appended to the end of the option, which my success function splits out of it and I use it on my front end to decide whether or not the option requires confirmation once selected. All good.
My problem occurs when the confirm dialog comes up, it crashes IE 11 no matter the chosen option. It works fine in Chrome and Firefox, but crashes every time in IE. My only thought is that IE doesn't like that this is all done in an AJAX success function? Not sure. Any ideas would be greatly appreciated! Thank you.
$('.lazy-load').click(function (e, k) {
if (e.currentTarget.length < 2) {
var callerId = getTarget(e);
callerId = callerId.id;
// parse out the true encrypted id
var encIdIndex = callerId.indexOf('ddlAction') + 9;
var encId = callerId.substring(encIdIndex);
if (encId == '' || encId == null)
return;
// get the valid workflow options for this clientice
$.ajax({
type: 'POST',
url: 'LandingSummary.aspx/GetWorkflowOptions',
async: false,
data: "{ 'csId': '{0}'}".format(encId),
success: function (data) {
ddlId = 'ddlAction' + encId;
$$(ddlId).get(0).options.length = 0; // clear
$$(ddlId).get(0).options[0] = new Option("Choose...", '');
$.each(data.d, function(index, item) {
if (item.Value.indexOf('CONFIRM') != -1) {
//strip text
var newText = item.Value.slice(0, 0 - 'CONFIRM'.length);
// add confirm attribute
var option = new Option(newText, item.Key);
option.setAttribute('data-confirm', 'confirm');
$$(ddlId).get(0).options[$$(ddlId).get(0).options.length] = option;
}
else {
$$(ddlId).get(0).options[$$(ddlId).get(0).options.length] = new Option(item.Value, item.Key);
}
});
var fullId = $$(ddlId)[0].id;
ExpandSelect(fullId);
// add warning hookup
$$(ddlId).change(function () {
var confirmAttribute = $$(ddlId).find('option:selected').attr('data-confirm');
//debugger;
if (confirmAttribute != undefined) {
var newState = $$(ddlId).find('option:selected').text();
var sure = confirm('Are you sure you want to move this authorization to the {0} state?'.format(newState));
if (!sure) {
$$(ddlId).val('');
return false;
}
}
});
},
error: function (result) {
alert('error retrieving workflow options');
}
});
}
return false;
})
function getTarget(obj) {
var targ;
var e = obj;
if (e.target != undefined) targ = e.target;
else if (e.srcElement != undefined) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
return targ;
}
});
Problem signature:
Problem Event Name: APPCRASH
Application Name: IEXPLORE.EXE
Application Version: 11.0.9600.17631
Application Timestamp: 54b31a70
Fault Module Name: MSHTML.dll
Fault Module Version: 11.0.9600.17631
Fault Module Timestamp: 54b33039
Exception Code: c0000005
Exception Offset: 0008d910
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 1033
Additional Information 1: 0a9e
Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
Additional Information 3: 0a9e
Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

Run Javascript function before jQuery functions

I am trying to be able to get my form to check if the 2 input boxes have any data input into them before it submits. The reason I am having trouble with this is because I am using the following -
$('form.ajax').on('submit', function () {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
})
this.reset();
return false;
});
This makes it so the form is submitted without the page having to refresh, I also have an image appear for a few seconds when the submit button has been pressed -
$(".bplGame1Fade").click(function(){
$("#bplGame1ThumbUp").fadeIn(1000);
$("#bplGame1ThumbUp").fadeOut(1000); });
I don't want these to run unless both the input boxes have data in them. I have tried using OnClick() and OnSubmit(). When using these the message appears saying it isn't a valid entry as I want but once you click OK the form continues to submit.
Is there anyway I can run a JS function to check the input boxes and if one of the boxes is empty, cancel the submission.
Any help with this would be appreciated,
Thanks.
Why dont you just add an if condition to check if you ever get an empty input? You can return the function if it's not valid.
$('form.ajax').on('submit', function () {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
var context = this;
var valid = true;
var total = that.find('[name]').length;
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if (!value) {
valid = false;
return;
}
data[name] = value;
if (index === total - 1) { //last item
if (valid) {
$.ajax({
url: url,
type: method,
data: data,
});
context.reset();
}
}
});
});
EDIT: You could put the ajax call inside of the foreach. So on the last item, you would make the ajax call if every input had a value.

Using javascript to check true/false condition on viewmodel

I am using local storage variable to hold the location of a users current progress. I have ran into a problem whereby if the last section that the user was on has been since deleted I am getting a target invocation must be set error. This is my code:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
I need to check using javascript that the localStorage course section is still existing in the database so I created the following ViewModel method:
public bool CourseSectionLaunchStillExistCheck(int courseSectionID)
{
this.TargetCourseSection = courseSectionRepository.Get(cs => cs.CourseSectionID == courseSectionID).FirstOrDefault();
if (this.TargetCourseSection != null)
{
return true;
}
else
{
return false;
}
}
But when I try to use the following javascript:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
if ('#Model.CourseSectionLaunchStillExistCheck(id)' != true) {
var id = '#Model.CourseSections.First().CourseSectionID';
}
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
It is failing to recognise the id parameter saying it does not exist in the current context. How can I ensure that the course section exists using javascript before setting the variable?
Could I use a post such as:
var postData = { 'courseSectionID': id };
$.post('/Course/CourseSectionLaunchStillExistCheck/', postData, function (data) {
});
and then how could i check if the result of this post data would be true or false?

Categories