POST JSON to controller with jquery and also use built in validation - javascript

I have a form which collects some data, most importantly an address which needs to be geocoded to obtain the lat and long.
Suppose the user inputs something like:
123 main st
SomEwheRE, NY 12345
My client-side javasript goes out to the Google Geocoding service and attempts to get the lat and long for that address. In return I also get back more addition information including the properly formatted address:
123 Main St
Somewhere, NY 12345
What I want to do is replace the values in their respective textboxes so that the user can verify the data is good and then finally submit via jQuery.post("My/Controller/", myJSONData, function(){}); but I'm getting some strange behavior.
If I type in an address and don't include a zip code (it's required in the database but not necessary to geocode the address) I get a validation error. The thing is I would like to defer validation until after I obtain the information from the geocode service and replace the values in the textbox.
Right now, if I only type in a partial address (and hit "Submit") this is what happens:
Validation errors occur on the missing required fields and all my textboxes go blank
Hit submit again and this time the textboxes are properly filled in with the geocoded information BUT ALL fields produce validation errors.
Hit submit a 3rd time and now the validation errors go away and everything is as expected. At this point, I want to consider the form valid and allow the POST to the Controller.
Code:
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
var geoCodedAddress = geoCodeAddress($("#Address1").val(), $("#City").val(), $("#State").val());
console.log(geoCodedAddress);
geoCodedAddress.Name = $("#Name").val();
geoCodedAddress.Phone = $("#Phone").val();
$("#Address1").val(geoCodedAddress.Address1);
$("#City").val(geoCodedAddress.City);
$("#State").val(geoCodedAddress.State);
$("#ZipCode").val(geoCodedAddress.ZipCode);
});
});
geoCodeAddress() returns the JSON object with the required fields filled in and that works. I believe the problem lies somewhere between my ineptitude and the block of code I posted.

Well, after much tinkering this is what I came up with. Basically, when someone hits submit (or enter) I stop the form from being submitted (by e.preventDefault()) and check to see if it's valid. If the form data is valid, I then process what the user entered, fill in the form fields with the acquired data (this doesn't do anything functional, it just flashes the new data in the form). I couldn't figure out how to submit the form, so I posted it myself using $.post(). If there is a better way please leave a comment or answer and I will vote. Here is my complete code:
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
if ($("form").valid()) {
geoCodeAddress($("#Address1").val(), $("#City").val(), $("#State").val(), function (geoCodedAddress) {
geoCodedAddress.Name = $("#Name").val();
$("#Address1").val(geoCodedAddress.Address1);
$("#City").val(geoCodedAddress.City);
$("#State").val(geoCodedAddress.State);
$("#ZipCode").val(geoCodedAddress.ZipCode);
$("#Longitude").val(geoCodedAddress.Longitude);
$("#Latitude").val(geoCodedAddress.Latitude);
$.post("/Controller/Action/", geoCodedAddress, function () { $(window).attr("location", "/Controller/"); });
});
}
});
});

Related

Update value of INPUT in externally loaded FORM not working

total programming novice here - I don't know much of javascript, wasn't programming since university (about 10 years ago) - trying to solve one specific problem on my website.
I am using CRM Bitrix24 and I have an unsubscribe form from this CRM placed on my website. I need to setup the form the way that the email is loaded from URL parameter.
I have done that simply by loading the input and set input.value = "email from URL". My problem is that the form has some kind of validation, and even though there is a text filled in the input field, the form is giving me the error: Field is required.
Screenshot here: https://ibb.co/Ns33GVN
The code of external form look like this:
<script data-b24-form="inline/120/8y7xg2" data-skip-moving="true">(function(w,d,u){var s=d.createElement('script');s.async=true;s.src=u+'?'+(Date.now()/180000|0);var h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);})(window,document,'https://cdn.bitrix24.com/b7014957/crm/form/loader_120.js');</script>
My JS:
function emailPopup(){
var params = new window.URLSearchParams(window.location.search);
var email = params.get('email');
const emailCollection = document.getElementsByName("email");
for (let i = 0; i < emailCollection.length; i++) {
if (emailCollection[i].name == "email") {
//emailCollection[i].focus();
emailCollection[i].value = email;
}
}
} window.addEventListener('load', function () {
emailPopup();
})
I tried to understand how the validation is done, but with no luck. The field has autocomplete = yes, so once it is submitted, next time it's not shooting the error, but the form is sent with the email submited at the first attempt, even though it is showing another one when hitting the SUBMIT button. It seems like it's only showing the email address from URL parameter, but in fact it's using wrong value, it's even empty (first attempt) or wrong (second attempt).
Is there a way how to force the field to pretend it was modified by user? Any ideas?
I have tried to setup similar environment here in jsfiddle: https://jsfiddle.net/e395wf6m/17/
Thanks a lot for any feedback!
I have a theory and it seems to be correct, as I tested it in your fiddle.
My theory is that the validation is done by firing a change event, so you need to trigger it. Luckily JavaScript let us do it:
if (emailCollection[i].name == "email") {
//emailCollection[i].focus();
emailCollection[i].value = email;
// to trigger the change event
emailCollection[i].dispatchEvent((new Event('change')));
}
As I said, it worked when I tested it on your fiddle, let me know if it works for you =]

How can I raise the alarm after unsuccessful text validation after clicking (addSubmitButton) "Send" button in SuiteScript?

I am new to SuiteScript and I am looking for some help with this problem. I need to do a simple validation that will throw an alert() when the company's vat number entered in the text box is incorrect (without "-", space, and a specified length).
This is for SuiteScript 1.0 API.
function findCompanyVATNumber(request, response){
//Here is a non-valid code
if(request.getMethod() === 'GET')
{
var form = nlapiCreateForm('Look for companies in the system', false);
var vatNumber = form.addField('custpage_taxnumber', 'text', 'Comanies vat number:', null, null);
vatNumber.setDefaultValue('');
form.addSubmitButton('search');
response.writePage(form);
}else{
//Here is a non-valid code
}
}
I expect that alert box will appear with information whats wrong with number if the entered value does not match the given function, and if the entered vat number is correct, the addSubmitButton will work like usual and will go to the page displaying information about the company.
You'll need to attach a Client Script to your Form object, and that Client Script will need to implement a handler for the saveRecord event. There is a method on nlobjForm for attaching a Client Script; see the Help documentation for the object for more details.
FWIW I advise you write any new code in SuiteScript 2.0, rather than 1.0.

How to detect Event Listeners and their actions on input fields

I have purchased a booking plugin (wordpress) to add to a site.
https://wpamelia.com/
I cannot show the site I am working on, but here a demo from plugin developers
https://sports.wpamelia.com/#book
Once you have chosen your date and time, you end up on a form with input fields.
I was able to pre-fill this form with data that I could pass via the URL.
My URL would look something like this: https://sports.wpamelia.com/?first=Jim&last=Tester&email=something%40something.com&phone=0222222222#book
But here is the problem:
Even though I managed to use jQuery to pre-fill the input fields of the form, as soon as I click confirm the fields' content is erased and the error "Please enter... " appears for each of them.
So again:
STEP 1: I open the booking page with an URL containing data in the query string
STEP 2: Using jQuery, I manage to pre-fill the form that appears after having chosen date and time (first name, last name ...)
STEP 3: I click "Confirm"
RESULT: all the fields are empty and for each one the error message "Please enter first name" (etc..) appears
I've messaged the plugin developers. Only answer was that there is indeed no functionality to take the data from the Query String into the form fields yet.
MY QUESTIONS:
1) How could I find out, with chrome inspector or other tools, why exactly the content I pre-fill into the form is ignored?
---> I've tried things like getEventListeners in the chrome inpector's console, but I don't really see how to get information out of that
2) Would anyone know what the issue is and/or how I could bypass it?
---> there is a lot of javascript from the plugin developers behind that and something is expecting manual entering of the data into the fields...
---> but even when trying to fake manual entering with things like $(this).trigger("change").val(function(i,val){return 'aaaa';}); this didn't solve the problem....
(If anyone is interested, I can post later my javascript/jQuery functionality to get the form fields pre-filled with data from Query String... interesting code as you have to wait until the fields appear for jQuery to recognise them..)
Thanks so much for any help!
cheers
Admino
#Admino - this may not be the best solution and I know this is an old question so you may not need it now but after not finding a better one it at least worked for me.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function valueOutput(element) {
element.dispatchEvent(new Event('input'));
}
jQuery(function() {
jQuery(document).on('change', 'input', function(e) {
valueOutput(e.target);
});
// you may want to perform more validations here if needed
// just checking here if email is present (but not checking for valid email address)
var fname = getUrlVars()["first"];
var lname = getUrlVars()["last"];
var email = getUrlVars()["email"];
var phone = getUrlVars()["phone"];
var custom1 = getUrlVars()["custom1"]; // you know this field label is Order Number
if (email.length > 0) {
// run an interval until the elements are present on the page (form displayed)
var checkInputs = setInterval(function() {
if (jQuery('.amelia-app-booking label[for="customer.email"]').length > 0) {
var em = jQuery('.amelia-app-booking label[for="customer.email"]').closest('.el-form-item').find('.el-input__inner');
// this checks to see if an Amelia customer is already present
if (em.val() == '') {
em.prop('value', email).val(email).trigger('change');
jQuery('.amelia-app-booking label[for="customer.firstName"]').closest('.el-form-item').find('.el-input__inner').prop('value', fname).val(fname).trigger('change');
jQuery('.amelia-app-booking label[for="customer.lastName"]').closest('.el-form-item').find('.el-input__inner').prop('value', lame).val(lame).trigger('change');
jQuery('.amelia-app-booking label[for="customer.phone"]').closest('.el-form-item').find('.el-input-group__prepend').siblings('.el-input__inner').prop('value', phone).val(phone).trigger('change');
}
// for custom fields I check the label text to find the correct input
if (custom1 != '') {
jQuery('.amelia-app-booking label:contains("Order Number")').closest('.el-form-item').find('.el-input__inner').prop('value', custom1).val(custom1).trigger('change');
}
// form info is updated so clear the interval
clearInterval(checkInputs);
}
}, 500);
}
});
You may want to try a different method than url params to sync this info so it's not so public in the url string. This code may not need both the prop and val jquery setters but I just left them for you to try. Hope it helps (and to others I'm open to a better solution)!

Form input to http post request

I have an Angular Bootstrap project- a form with some fields like name, email, phone, etc. to fill in. The form is written in HTML, in a file called customer-form.component.html. Upon submission, a JSON object is created with the values of the fields and displayed on-screen.
I am writing a HTTP POST request in the file customer-form.component.ts. The method in question looks like this:
postProfile() {
this.httpClient.post('API server url',
{
name:this.name,
phone:this.phone,
email:this.email,
yesorno:this.yesorno
})
.subscribe(
(data:any) => {
console.log(data)
}
)}
I set it up so submission of the form would also submit the POST request to the server. I am using Chrome to debug, and in the console I get the error message:
"Failed to INSERT or UPDATE Customer record due to: [com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'NAME' cannot be null]"
I changed the code to name:name once, and a submission got through. But when I checked it in the server, it had a blank name (name:''), and some true/false fields and fill-in numerical fields. Email and phone were not even represented, blank or otherwise, in the submission. Now if I try to submit something with name:name, it is counted as a duplicate and does not work. No matter what I fill in the form before I submit, the complaint is that the name field is blank.
My main question: Is there a way, preferably by referring to the JSON object, to accurately populate the POST request fields based on input fields? The JSON object is defined/created in a script in the index.html file.
My second question: What on earth is being used to populate the POST request right now? Even if I fill in the fields, the name field is blank upon submission. I have a model Customer object in customer-form.component.ts (like below), and I suspect that is how the original submission was populated (except the name?).
model = new Customer('Harry', 11111111111111, 'pott#r', true);
Please let me know if more information is needed.

Javascript driven forms in Django

Django uses his forms API for input validation. The form is sent to the template, and it is rendered as an html (as_p and friends).
When the user is ready, he POST the form, the data is validated, and the form is re-rendered on the template if it is not valid.
This is odd when the form is not valid just because lack of enough caracteres (i.e. min_length) on a field or invalid characters: one POST too much just to tell the user it is missing something very basic.
So, is there any available way (Django or app) of rendering a form with javascript code that "tests"[*] some of the form' fields on the client-side? I.e. have a form which is rendered as_javascript(...) that dynamically shows error messages that would be shown by form.errors?
This should not work for all fields because some require a database hit, but it should work on simple (and most common) fields, namely CharField, TextField, etc.
[*] "tests" because validation has always to be made also on the server-side.
So you want to validate something in JS before submitting. Here's one way to do that.
Instead of putting an input of type submit in the form you should put a button of type button:
<form id="my-form" submit="...">
...
<input type='button' id='submit-button' value="Save">
</form>
Note that unless you specify the type as "button", it will still try to submit.
Then in a JS file you write something like this (include jQuery in your HTML file):
$('#submit-button').click(function() {
var errors = testErrors(); // this function tests for the errors.
if (errors != "") {
alert(errors);
} else {
$('#my-form').submit();
}
}
Example testErrors():
function testErrors() {
var country = $("#id_country").val();
var city = $("#id_city").val();
var errors = "";
if (country == "") {
errors += "- Please select a country\n";
}
if (city.length <= 10 ) {
errors += "- Your city name is too short\n";
}
return errors;
}
So in testErrors you define your own tests for each field. In this example there are two, country and city. For country the code tests whether it's blank and for city whether it's longer than 10 characters. You can define further tests of your own. Please refer to jQuery documentation as well on how to retrieve values from different types of form fields.

Categories

Resources