Run Javascript function before jQuery functions - javascript

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.

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 validate serialized data in Ajax

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

Jquery - Create key value pairs from dynamic form submission

I am pretty new to jquery and can't seem to figure this issue out.
I need to figure out how to dynamically set the key:value pairs in this code below from a form that has dynamic values for form inputs. The code works if I add the key:value pairs manually, but I don't always know what the form names are going to be as they are created by the user.
Please see the notes in the middle section of code below. I am trying to use the values from .serialize() to pass as the $_POST value.
Here is the value I currently get from the var formValues:
ID=10&user_login=test9&wplp_referrer_id=&&block_unblock=u
However when I try to pull the values in my function using:
$user_id = $_POST['ID'];
The ID of '10' is not being set in $user_id, indicating that the syntax or method I am using to pass the serialized results is not correct below.
jQuery(document).ready( function($) {
$("#wplp_edit_member").submit( function() {
var formValues = $("#wplp_edit_member").serialize(); //Get all the form input values
alert(formValues); //Check form values retrieved for testing only
var numbers = /^[0-9]+$/;
// Validate fields START
var wplp_referrer_id = $("#wplp_referrer_id").val();
if( !wplp_referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Post data to ajaxurl
$.post(ajaxurl, {
action: "wplp_edit_member", //Call the PHP function to update/save form values
data: formValues, //Use data to pass form field values as $_POST values to the function above
// No More manual inputs of form fields to be passed
//ID:$("#ID").val(),
//user_login:$("#user_login").val(),
//wplp_referrer_id:$("#wplp_referrer_id").val(),
//block_unblock:$("#block_unblock").val(),
},
// Success
function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
}
);
return false;
});
});
Thanks!
If you want to post data as json, you can use a variation of $.fn.serialize(), Add the jquery extension,
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and use it as,
var data = $('#some-form').serializeObject(); //the dynamic form elements.
data.action = "wplp_edit_member";
$.post(ajaxurl, data, function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
});
If posting json is not your requirement $.fn.serializeArray can work.
hope this helps.
What you want is to dynamically add properties to a javascript object. How this can be done is all over the web, but also demonstrated here:
Is it possible to add dynamically named properties to JavaScript object?
so in your case, you would set your object up first before calling .post:
var formData = {};
for (...) {
formData[...] = ...;
}
$.post(ajaxurl, formData, function (data) {
...
});
One way you might accomplish the iteration above is to just collect values from all inputs between your <form> tags:
$('form input').each(function ($input) {
formData[$input.attr('name')] = $input.val();
});
There are lots of ways to skin this cat. Also, jQuery has lots of plugins that might be of help here, although usually YAGNI (You Aren't Going To Need It), so just KISS (Keep It Simple, Stupid).
Here is the solution I was able to get working based on the code provided by #shakib
jQuery(document).ready( function($) {
$("#wplp_edit_member").submit( function() {
var numbers = /^[0-9]+$/;
var wplp_referrer_id = $("#wplp_referrer_id").val();
// Validate fields START
if( !wplp_referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var data = $('#wplp_edit_member').serializeObject(); //the dynamic form elements.
data.action = "wplp_edit_member";
$.post(ajaxurl, data, function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
});
return false;
});
});
This is actually a very simple implementation if you understand Jquery/Javascript! ;o)
Thank you to everyone for your input!

How to convert simple form submit to ajax call;

I have a form with input field which can be accessed like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
and earlier call was
document.forms["algoForm"].submit();
and form was
<form name="algoForm" method="post" action="run.do">
It all run fine
Now I wanted convert it to the ajax call so that I can use the returned data from java code on the same page. So I used soemthing like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
var data = 'algorithm = ' + algorithm + '&input = ' + input;
$.ajax(
{
url: "run.do",
type: "POST",
data: data,
success: onSuccess(tableData)
{ //line 75
alert(tableData);
}
}
);
However the above code doesn't run. Please help me make it run
Let's use jQuery's serialize to get the data out of the form and then use the jQuery's ajax function to send the data to the server:
var data = $("form[name=algoForm]").serialize();
$.ajax({
url: "run.do",
type: "POST",
data: data,
success: function(tableData){
alert(tableData);
}
});
data expects a literal object, so you need:
var data = {
'algorithm': algorithm,
'input': input
};
Instead of retrieving all the parameter value and then sending them separately (which can be done server side as well, using below code), Use this:
var $form = $("#divId").closest('form');
data = $form.serializeArray();
jqxhr = $.post("SERVLET_URL', data )
.success(function() {
if(jqxhr.responseText != ""){
//on response
}
});
}
divId is id of the div containing this form.
This code will send all the form parameters to your servlet. Now you can use request.getParameter in your servlet to get all the individual fields value on your servlet.
You can easily convert above jquery post to jquery ajax.
Hope this helps :)
// patching FORM - the style of data handling on server can remain untouched
$("#my-form").on("submit", function(evt) {
var data = {};
var $form = $(evt.target);
var arr = $form.serializeArray(); // an array of all form items
for (var i=0; i<arr.length; i++) { // transforming the array to object
data[arr[i].name] = arr[i].value;
}
data.return_type = "json"; // optional identifier - you can handle it on server and respond with JSON instead of HTML output
$.ajax({
url: $form.attr('action') || document.URL, // server script from form action attribute or document URL (if action is empty or not specified)
type: $form.attr('method') || 'get', // method by form method or GET if not specified
dataType: 'json', // we expect JSON in response
data: data // object with all form items
}).done(function(respond) {
console.log("data handled on server - response:", respond);
// your code (after saving)
}).fail(function(){
alert("Server connection failed!");
});
return false; // suppress default submit action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I don't know how but this one runs well,
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
$.post('run.do', {
algorithm : algorithm,
input : input
}, function(data) {
alert(data);
}
);

How to use dynamic data name with jQuery.post?

I have 2 basic form used to convert data (type 1 <-> type 2).
I want to do my .post request using only 1 form.
I'm having issue with the [data] parameter for jquery.post
Here's my code :
$('form').submit(function(){
var a = $(this).parent().find("input").attr('name');
var b = $(this).parent().find("input").val();
var url = $(this).attr('action')
$.post(url, { a:b },function(data) {
$(data).find('string').each(function(){
$('.result').html($(this).text());
});
});
return false;
});
The problem lies within {a:b}.
b is interpreted as my var b, but a isn't, making my post parameters something like [a:1] instead of [param:1].
Is there a way to have a dynamic a?
Try this:
var data = {};
data[a] = b;
$.post(url, data, function(data) {
So like this:
$('form').on('submit', function (e) {
e.preventDefault();
var data = {};
var el = $(this);
var input = el.parent().find('input');
var a = input.attr('name');
var b = input.val();
var url = el.attr('action');
data[a] = b;
$.post(url, data, function(data) {
$(data).find('string').each(function(){
$('.result').html($(this).text());
});
});
Yes, use something else for the data post:
$.post(url, a+"="+b,function(data) {
$(data).find('string').each(function(){
$('.result').html($(this).text());
});
});

Categories